How do I know when I have to call StateHasChanged() in Blazor?
In a typical scenario, let's say I am loading data and I want the "Load" button to be disabled while it is loading. So perhaps I have the following. The behavior I see is that the button will appear enabled during initial load unless I call base.StateHasChanged()
on line 17; however, after that, if I click "load", the button will appear disabled while it is loading and then become enabled as expected. So why doesn't such work in the call from OnInitializedAsync? Is there an alternative approach that would enable me to omit StateHasChanged()?
@inject HttpClient Http
<div class="my-component">
<button disabled="@(LoadingTask?.IsCompleted == false)" @onclick="LoadData">Load</button>
...
</div>
@code {
protected override async Task OnInitializedAsync() => await LoadData();
private Task<Thing[]>? LoadingTask { get; set; }
private Thing[] Data { get; set; } = new Thing[0];
private async Task LoadData()
{
LoadingTask = Http.GetJsonAsync<Thing[]>(url);
// Line 17: I shouldn't need to call base.StateHasChanged() here, right?
funds = await LoadingTask;
HasLoaded = true;
}
}
It seems that OnInitializedAsync does not allow the component to rerender on awaits, unlike user-initiated events like OnClick. So it seems that calling StateHasChanged inside OnInitializedAsync is necessary unless Blazor gets more sophisticated with when to check for changes in future versions.