DrGriff
DrGriff

Reputation: 4916

Blazor - UI not updating whilst task executing

Using Blazor WebAssembly, along with the MudBlazor components.

I have a List<SomeClass> and a MudTable that is bound to it.

I have the following button:

<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="@(async () => await MyMethodAsync())">
    <MudText Class="ms-2">Run MyMethod</MudText>
</MudButton>

Which calls the following method:

private async Task MyMethodAsync()
{ ... }

What this method does is to have a loop in which it makes an awaited HTTP call and updates the above mentioned list (which is bound to the table).

So, pseudo code

for (int i = 0; i < 100; i++)
{
  HttpResponseMessage m = await Http.PostAsync(endpoint, data[i], _token);
  if (m.IsSuccessStatusCode)
  {
    string response = await serverResponse.Content.ReadAsStringAsync();
    _myListBoundToTable.AddRange(JsonSerializer.Deserialize<List<SomeClass>>(response);
  }
}

So....when this method has completed then the MudTable makes itself visibie with all the lovely data.

What I'd really like is that everytime I add data to the list within the loop then the MudTable rebinds and updates itself, so that the user may start viewing the data without having to wait for all the data to have been loaded.

Upvotes: 3

Views: 1152

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273784

The OnClick is an EventCallback, meaning the screen updates are normally handled automatically.

Conceptually, there is a StatehasChanged() call before and after the handling. You get up to 2 screen updates for free. But you have for (int i = 0; i < 100; i++) so you are missing 98 updates in the middle.

  if (m.IsSuccessStatusCode)
  {
     ... // as before
     StateHasChanged();  // add this
  }

Upvotes: 3

Related Questions