Adding a spinner to a Blazor application


My first project with Blazor was building a testing application for a test of APIs.  This was low risk while changeling enough to make it fun.  The application started simple, just submit a form of data to the API.  Seems simple enough.

I created the form, used a service to talk to the API and got it up and running fairly quick.  It was at this point that I realized the API was a long running process as far as the user is concerned.  Being the good developer, I decided to add a “spinner” to the UI to let the user know it was working.  This is when the fun started.

For the actual spinner, I just did a google search for a cool looking spinner.  The hardest part of that was choosing which one to use.

<div class="spinner @cursorCSS"></div>

I then wired it in to the Blazor Page:

    protected void Submit()
    {
        //Show Sending...
        cursorCSS = "";
        this.StateHasChanged();
        response = Service.Post(userModel);
        if (response.Errors.Any())
        {
            errorCss = "errorOn";
        }
        //turn sending off
        cursorCSS = "cursorSpinOff";
        this.StateHasChanged();
    }

Ran my test and the spinner did not show .  Through some debugging I noticed that if I removed the cursorSpinOff line of code the spinner would show but after the Service Post ran.

After some time on Stack OverFlow and a thanks to Dani Herrera, I found out I was trying to refresh the UI thread with the this.StateHasChnaged, but I was on the UI thread.
So, I changed the method to be async and cleaned up the code around the spinner:

    protected async Task Submit()
    {
         spinning=true;
         response = Service.Post(userModel);
         if (response.Errors.Any())
        {
           errorCss = "errorOn";
        }
        spinning=false;
        await Task.CompletedTask; // just to avoid non await warning.
    }

For the spinner:
  @if (spinning)
  {
      <div class="spinner"></div>
  }

Now the button clicks calls the Submit Method on the UI thread, that spawns off the service post to its own thread, the UI thread continues, and page is refresh showing the Spinner.
Once the service post is done, the spinner variable is set to false the page is updated tuning off the spinner.

Now the user has some feedback on when we are calling the server side post.



Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor - Cool Blur Loading Page

Blazor new and improved Search Box