How To Isloading

Published on Saturday, December 30, 2023

How To: IsLoading

I�ve seen many variations of this that don�t work; specifically, setting and clearing the _isLoading field inside a synchronous method � that won�t do anything because the component doesn�t re-render unless there is an await.

private async Task AsyncLongFunc() // Must be async task
{
  _isLoading = true; // This field is used the razor file to show the spinner
  try
  {
    if (HaveSomeAsyncWorkToDo)
    {
      await DoSomeAsyncWork();  // Must await an async task...
    }
    else
    {
      await Task.CompletedTask; // ...at some point for isLoading to work
      DoSomeSyncWork();
    }
  }
  catch // Optional, but a good idea
  {
    // Some error handling
  }
  finally // Important to turn off _isLoading, even in the case of an exception
  {
    _isLoading= false;
  }
}