Home > Back-end >  Blazor Server App - How is this loading progress working, is it in a loop
Blazor Server App - How is this loading progress working, is it in a loop

Time:10-15

Disclaimer: New to Blazor.

How is the loading... message working? Is this page in a loop of some sort?

@page "/fetchemployees"
@inject SampleDataAccess data


<PageTitle>Employee Directory</PageTitle>

<h1>Employee Directory</h1>

@if (employees is not null)
{
    foreach (var e in employees)
    {
        <h3>@e.FirstName @e.LastName</h3>
    }

}
else
{
    <h3>Loading...</h3>
}

@code {
    List<EmployeeModel> employees;

    //protected override void OnInitialized()
    //{
    //    employees = data.GetEmployees();
    //}

    protected override async Task OnInitializedAsync()
    {
        employees = await data.GetEmployeesCache();
    }
}

CodePudding user response:

Below is a rough description of what is going on...Any detailed description may lead you astray. When you feel sure enough, go to the code source, and follow the steps that are performed to create a Blazor component...

One of the first life cycle methods involved in the creation of a Blazor component is the OnInitialized{Async} pair.

When you're component is being rendered, the OnInitializedAsync method is executed... When the line of code: await data.GetEmployeesCache() is encountered, the data.GetEmployeesCache() method is awaited, that is, it is called, and the execution control is yielded to the calling code; the calling code here, is the Blazor framework that takes control of the execution of the code... The framework starts rendering the view portion of the component; that is the UI. When the framework encounters the statement: @if (employees is not null), it renders the Razor markup: <h3>Loading...</h3>, which is why you see the text Loading... on the screen... When data.GetEmployeesCache() returns (completes), and a value is assigned to the employees list (not null any longer), the framework re-renders the component once more, this time the employees variable is no longer null, and thus the foreach loop is executed, and the razor markup is rendered.

The above description is simplified in order to convey the general idea of what is going on, without mentioning any other life cycle methods, the StateHasChanged method, etc. The idea is to understand how a Blazor component is rendered, and the role of asynchronity applies here to achieve the rendering of the message and after that of the list of employees.

  • Related