Home > Backend Development > C++ > How to Display a Spinner During Long-Running API Calls in Blazor?

How to Display a Spinner During Long-Running API Calls in Blazor?

Patricia Arquette
Release: 2024-12-28 10:53:10
Original
912 people have browsed it

Displaying Wait or Spinner During API Calls in Blazor

Blazor enables you to display feedback to the user during long-running API calls using visual cues like wait cursors or spinner images.

Issue:

In your Blazor application, you attempted to use CSS to display a spinning cursor during API calls. However, the page content was not refreshed until the call was completed.

Solution:

Option 1: Using Task.Delay(1)

  • Create an asynchronous method.
  • Use await Task.Delay(1) or await Task.Yield(); to force the UI to update before the API call completes.
private async Task AsyncLongFunc()    // this is an async task
{
    spinning=true;
    await Task.Delay(1);      // flushing changes. The trick!!
    LongFunc();               // non-async code
    currentCount++;
    spinning=false;
    await Task.Delay(1);      // changes are flushed again    
}
Copy after login

Option 2: Using Task.Run() (Not for WebAssembly)

  • If your LongOperation() method is not async, enclose it in a Task and await it using Task.Run().
async Task AsyncLongOperation()    // this is an async task
{
    spinning=true;
    await Task.Run(()=> LongOperation());  //<--here!
    currentCount++;
    spinning=false;
}
Copy after login

Effect

How to Display a Spinner During Long-Running API Calls in Blazor?

Note for Server-Side Prerendering:

In Blazor Server apps, the spinner will not appear due to prerendering. To make it visible, perform the long operation in OnAfterRender.

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {           
        await Task.Run(()=> LongOperation());//<--or Task.Delay(0) without Task.Run
        StateHasChanged();
    }
}
Copy after login

For more examples and information, refer to open source projects like BlazorPro.Spinkit.

The above is the detailed content of How to Display a Spinner During Long-Running API Calls in Blazor?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template