3.0 KiB
sidebar_position | title |
---|---|
4 | Use data |
Retrieve data
In order to use the data in the fake-data.json
file, we will use the GetFromJsonAsync
method of the HttpClient
object.
This method allows to obtain and to convert (Deserialization) the data of the file in a list containing our data.
Add default http client
Open the Program.cs
file and add the highlighted line.
builder.Services.AddSingleton<WeatherForecastService>();
// highlight-next-line
builder.Services.AddHttpClient();
var app = builder.Build();
This addition allows to define an HttpClient
for the Blazor application.
Page code
Open the List.razor.cs
class and fill it as follows:
public partial class List
{
// highlight-start
private Item[] items;
[Inject]
public HttpClient Http { get; set; }
[Inject]
public NavigationManager NavigationManager { get; set; }
protected override async Task OnInitializedAsync()
{
items = await Http.GetFromJsonAsync<Item[]>($"{NavigationManager.BaseUri}fake-data.json");
}
// highlight-end
}
The OnInitializedAsync
method fires when the page is displayed, see the concept "Lifecycle events" further down this page.
Show data
First we will perform a simple display of our data.
To do this, open the List.razor
file and fill it in as follows:
@page "/list"
<h3>List</h3>
// highlight-start
@if (items != null)
{
foreach (var item in items)
{
<div>@item.Id</div>
}
}
// highlight-end
You have now displayed the list of the value of the Id
field in your page.
:::caution
Be careful, remember to check if your list is not null before doing your foreach
. Otherwise an error will be thrown.
:::
Concept: Life cycle events
The following diagrams illustrate the Razor component lifecycle events.
Component lifecycle events:
- If the component is rendered for the first time on a request:
- Create the component instance.
- Perform property injection. Run
SetParametersAsync
. - Call OnInitialized{Async}. If an Incomplete Task is returned, the Task is awaited, then the component is re-rendered.
- Call OnParametersSet{Async}. If an Incomplete Task is returned, the Task is awaited, then the component is re-rendered.
- Render for all synchronous jobs and all Tasks.
Document Object Model (DOM) event processing:
- The event handler is executed.
- If an Incomplete Task is returned, the Task is waited for, then the component is re-rendered.
- Render for all synchronous jobs and all Tasks.
The Render lifecycle:
-
Avoid additional rendering operations on the component:
- After the first rendering.
- When ShouldRender is false .
-
Generate render tree (difference) and component render.
-
Wait for the DOM to update.
-
Call OnAfterRender{Async} .