0

I have a Blazor server site with a simple method that is supposed to do the following:

  • Start spinner on the button
  • Execute the SaveChanges,
  • Stop the spinner and display a message pop up alerting the user of the result,
  • Clear the message after 5 seconds.

Here is the code:

private async Task HandleValidSubmit() {
  // Start spinner
  Icon = "spinner-border spinner-border-sm";
  try {
    Context.Update(Case);
    await Context.SaveChangesAsync();
    message = "Key info successfully updated";
    messageStatus = "success";
  } catch (Exception ex) {
    message = ex.Message;
    messageStatus = "danger";
  }

  // Stop spinner
  Icon = "k-icon k-i-save";
  await Task.Delay(5000);
  messageStatus = " d-none";
}

When running the method however, the spinner is shown for five seconds and no message appears. If I comment out the await Context.SaveChangesAsync(); it runs as expected.

Why is the spinner not stopping when the first await finishes, and why is the message not showing for 5 seconds? Does it have anything to do with having two await calls?

What am I doing wrong? Any help is appreciated.

aryeh
  • 610
  • 5
  • 13

1 Answers1

1

Becuase you're running updates to fields in an asynchronous method, there's a chance that when you change those values such as the message text - that the state isn't being updated on the page and the text and is not showing.

Try using await InvokeAsync(()=>StateHasChanged()); to tell the UI that it should update with new values.

DekuDesu
  • 2,224
  • 1
  • 5
  • 19
  • Your right, since the message is a field it won't get updated automatically. Do I need to use await InvokeAsync or can I just use StateHasChanged it seems to work fine without awaiting. What do I gain from awaiting it? – aryeh May 19 '21 at 17:20
  • As far as I'm aware `StateHasChanged` may have issues with executing with the wrong context(not running on the UI Thread) so `InvokeAsync` ensures its running on the right thread, that i believe. – DekuDesu May 19 '21 at 17:22
  • 1
    Thank you, I found this answer which explains it nicely https://stackoverflow.com/a/65231017/8337631 – aryeh May 19 '21 at 17:27