By utilizing browser storage in Blazor, you can effectively save and load data within a component. In the following example, you can see how the counter value is updated with a button click and the count value is stored in the local storage of the browser. When you refresh the page, the saved data will be loaded from the browser’s local storage.
[Index.razor]
@page "/"
@using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage
@inject ProtectedLocalStorage LocalStorage
@if (isCount)
{
<p>Current count: <strong>@currentCount</strong></p>
<button class="btn btn-primary" @onclick="IncrementCount">Increment</button>
}
else
{
<p>Loading...</p>
}
@code {
private int currentCount;
private bool isCount;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
isCount = true;
// Get the count value into browser local storage.
var countValue = await LocalStorage.GetAsync<int>("countValue");
// Loaded the browser local storage value to currentCount.
currentCount = countValue.Success ? countValue.Value : 0;
StateHasChanged();
}
}
private async Task IncrementCount()
{
currentCount++;
// Set the count value in browser local storage.
await LocalStorage.SetAsync("countValue", currentCount);
}
}
Refer to this link for more details.
Share with