Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to persist value in a singleton state container in blazor web assembly on page reload

I practicing and learning blazor web assembly. I'm learning on the ways to communicate between the components. One such way is to use a state container. This works as expected however it does not sustain value on page refresh.

Here is my state container class,

AppState:

public class AppState
{
    public string SomeText { get; set; }
}

I have registered this as a Singleton instance in Program.cs

builder.Services.AddSingleton<AppState>();

with this setup, I'm able to @inject AppState in multiple components and share the value like I can set it in one component and get it in another component. All goes well. When I refreshed, I lost the value in SomeText property.

After further googling, I noticed from this article - Service Lifetimes in Blazor that,

Blazor is running on the client only and a full page refresh or opening the app in a new tab creates a new instance of the application.

But is there any workaround or solution to retain the value? All that comes to my mind is browser localstorage. Am I doing correct? Your suggestions please and correct me if I'n wrong?

like image 226
fingers10 Avatar asked Nov 23 '25 09:11

fingers10


1 Answers

Reloading the page is the equivalent of shutting down an app and restarting it, anything in memory is gone.

I've not used it myself but I've heard Blazored/localstorage by @chrissainty is good. But the problem there is you'd have multiple tabs fighting to set the state to conflicting values.

So you'd either need inter-tab communication, which can be done with events Communication between tabs or windows

If possible though, use your client as the UI and have it communicate with a server (and then to a db) for persistence.

like image 80
Peter Morris Avatar answered Nov 25 '25 00:11

Peter Morris