Home > Blockchain >  Blazor .NET Show loading spinner on UI while doing a heavy query in background
Blazor .NET Show loading spinner on UI while doing a heavy query in background

Time:11-23

I have following code where i fetch results from SQL server. These are razor pages, blazor framework .Net

<button @onclick="Filter">Filter</button>

@{

async Task Filter() {
    await FetchFromDb();
}

This query runs for 18 seconds. So i want to show loading spinner. In blazor, you can use a predefined div with spinner class to do this.

<div > </div>

I want to use this div like following

@(IsLoading) {
<div ></div>
} else {

show results from query
}

For which i need to change the Filter function as follows

async Task Filter() {
    IsLoading = true;
    await FetchFromDb();
    IsLoading = false;
}

But I figured, that the whole process of changing IsLoading=true and Isloading=false is done in one go and i don't see a spinner.

Is there a way to change IsLoading=true, while Filter function is getting results from Db in await FetchFromDb(); ?

@(IsLoading) {
<div ></div>
} else {

show results from query
}


async Task Filter() {
    IsLoading = true;
    await FetchFromDb();
    IsLoading = false;
}

But this doesn't work. IsLoading doesn't get updated on changing IsLoading=True.

CodePudding user response:

This looks like:

async Task Filter() {
    IsLoading = true;
    await FetchFromDb();
    IsLoading = false;
}

isn't really an async code block.

You should be able to do this and it works:

async Task Filter() 
{
    IsLoading = true;
    await Task.Delay(1);
    await FetchFromDb();
    IsLoading = false;
}

On the assumption that Filter is being called from a UI event such as a button press this is what happens.

The Task.Delay yields control back to the UI event handler. It (the UI event handler) calls StateHasChanged and yields awaiting Filter. The Renderer gets processor time to service its render queue and runs the component render fragment and render the component

I'm assuming await FetchFromDb(); is a call into a database. Either FetchFromDb wraps a Task around a synchronous database call or you're using a database, such as SQLite, that does the same thing internally with it's exposed async library.

CodePudding user response:

Please check the below component.

Demo: https://demos.getblazorbootstrap.com/preload

@code {
    [Inject] protected PreloadService PreloadService { get; set; }

    private void GetEmployees()
    {
        try
        {
            PreloadService.Show();

            // TODO: call the service/api to get the employees
        }
        catch
        {
            // handle exception
        }
        finally
        {
            PreloadService.Hide();
        }
    }
}
  • Related