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(); } }
Additional Resources
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!