In the default example project for both server-side Blazor and WebAssembly Blazor projects, the Counter example resets to 0 every time you move between the pages. However, on the ASP.NET React example project, the Counter does not reset between page switches.
Is there a way for a component like the Counter to preserve state between page navigation in Blazor (at least for the WebAssembly project that isn't making any server calls)?
It looks like this exact scenario is discussed in https://learn.microsoft.com/en-us/aspnet/core/blazor/state-management?view=aspnetcore-3.0#client-side-in-the-browser
Seems Blazor just doesn't handle it out-of-the-box, but you just need to use localStorage
or sessionStorage
.
Using the Blazor.Extensions.Storage
NuGet package (https://github.com/BlazorExtensions/Storage):
@page "/counter"
@inject ISessionStorage SessionStorage
@using Blazor.Extensions.Storage.Interfaces
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
protected override async Task OnInitializedAsync()
{
currentCount = await SessionStorage.GetItem<int>("counter");
}
private async void IncrementCount()
{
currentCount++;
await SessionStorage.SetItem<int>("counter", currentCount);
}
}
I cover this in my article (works for server side Blazor as well as client side (WebAssembly) Blazor): Implementing State Management In Blazor
Add a class called CounterState.cs using the following code:
public class CounterState
{
public int CurrentCount { get; set; }
}
Register this class, using Dependency Injection, in the the Startup.cs:
services.AddScoped<CounterState>();
Add the following code to the top of the .razor code page:
@inject CounterState CounterState
Change the following code:
<p>Current count: @currentCount</p>
To:
<p>Current count: @CounterState.CurrentCount</p>
Finally, change the code section to the following:
@code {
void IncrementCount()
{
// ** SESSION STATE
int CurrentCount = CounterState.CurrentCount;
CurrentCount++;
// Set Current count on the Session State object
CounterState.CurrentCount = CurrentCount;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With