Home > Backend Development > C++ > How to Display a Loading Indicator During API Calls in Blazor?

How to Display a Loading Indicator During API Calls in Blazor?

Mary-Kate Olsen
Release: 2024-12-31 16:40:18
Original
557 people have browsed it

How to Display a Loading Indicator During API Calls in Blazor?

Display Loading Indicator During API Calls in Blazor

When making API calls that may take some time in Blazor, it's important to provide feedback to the user. Commonly used indicators are a wait cursor or a spinner image. To achieve this in Blazor, several options are available.

Option 1: Using Task.Delay(1)

This method involves using an asynchronous task and calling await Task.Delay(1); or await Task.Yield(); after each UI update. This flushes changes and allows the spinner to be displayed.

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

This option involves creating a long-running operation in a task using Task.Run(()=> LongOperation());. This prevents the main thread from being blocked while the operation executes.

Effect of Spinner on Server-Side Prerendering

In Blazor Server apps, where pages are pre-rendered, the spinner will not be visible unless the long operation is performed in OnAfterRenderAsync. Using this lifecycle method instead of OnInitializedAsync ensures that server-side rendering is not delayed.

Sample Code

// Don't do this
//protected override async Task OnInitializedAsync()
//{
//    await LongOperation();
//}

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

Additional Resources

  • [BlazorPro.Spinkit](https://github.com/EdCharbeneau/BlazorPro.Spinkit) provides a library with sample code for creating spinners.

The above is the detailed content of How to Display a Loading Indicator During 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