3

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;
  }

}
Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129
  • Does this answer your question? [When I should call StateHasChanged and when Blazor automatically intercepts that something is changed?](https://stackoverflow.com/questions/60096040/when-i-should-call-statehaschanged-and-when-blazor-automatically-intercepts-that) – Quango Apr 01 '20 at 21:56
  • No, I still don't quite understand why await couldn't or shouldn't allow the UI to re-render--unless the answer is simply "it could but it doesn't." – Patrick Szalapski Apr 28 '20 at 19:50

2 Answers2

-2

When you want to update the state of a ChileContent,you shoul call StateHasChanged() in it's Parent Component.

-3

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.

Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129