The Be Sure Blog

Code Snippets | Problem Solving | Tips & Tricks

The Be Sure Blog banner

Set up a global state service in Blazor (Wasm)

posted on 24.3.2023 by Below Surface in "Blazor"

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!

Tags:

blazor
c#
global state
state management

Sources:

https://www.c-sharpcorner.com/article/how-to-use-state-management-in-blazor/

More posts of this category

Four reasons why I dislike Blazor as a React developer

After six months of working with Blazor, this is what i dislike about it

Blazor

How to get the last part of the url as a string

A little code snippet to get whatever comes behind the last slash of the url

Blazor