By using browser storage in Blazor, we can save and load data within a component. The following example demonstrates that the counter value is updated with a button click and the count value stored in local storage. When you refresh the page, the saved data will load from the browser 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