I wanted to implement something similar to Redux, which I'm familiar with from my React projects. The implemented feature makes it possible to store state globally. That means the state (variables) are accessible and changeable from everywhere in the application and will remain persistent until the whole app gets reloaded.
In this example we extend the Blazor Wasm example counter functionality, to be stored globally.
Step 1: Create the global state service file in your Blazor client root directory (e.g. /Services/GlobalStateService.cs)
namespace GlobalStateBlazorWasm.Services { public class GlobalStateService { public event Action? OnStateChange; public int CurrentCount { get; set; } = 0;public void IncrementGlobalCount() { CurrentCount++; NotifyStateChanged(); }
public void DecrementGlobalCount() { CurrentCount--; NotifyStateChanged(); }
private void NotifyStateChanged() => OnStateChange?.Invoke(); } }
Step 2: Register the GlobalStateService in your Program.cs file:
builder.Services.AddSingleton<GlobalStateService>();
Step 3: Modify the Counter.razor file:
@page "/counter"@using GlobalStateBlazorWasm.Services
@inject GlobalStateService GlobalStateService
<PageTitle>Counter</PageTitle>
<h1>Counter</h1>
<p role="status">Current count: @GlobalStateService.CurrentCount</p>
<button class="btn btn-primary" @onclick="@GlobalStateService.IncrementGlobalCount">+1</button> <button class="btn btn-primary" @onclick="@GlobalStateService.DecrementGlobalCount">-1</button>
Step 4: Modify Index.razor to see and change the global counter value there aswell
@page "/"@using GlobalStateBlazorWasm.Services
@inject GlobalStateService GlobalStateService
<PageTitle>Index</PageTitle>
<h1>Hello, world!</h1>
Welcome to your new app.
<SurveyPrompt Title="How is Blazor working for you?" />
<h1>Counter</h1>
<p role="status">Current count: @GlobalStateService.CurrentCount</p>
<button class="btn btn-primary" @onclick="@GlobalStateService.IncrementGlobalCount">+1</button> <button class="btn btn-primary" @onclick="@GlobalStateService.DecrementGlobalCount">-1</button>
For more information about how this works, check the provided source below!