3

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?

fingers10
  • 6,675
  • 10
  • 49
  • 87

1 Answers1

2

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.

Peter Morris
  • 20,174
  • 9
  • 81
  • 146
  • Reloading is equivalent to shutting down the app and restarting. This means program.cs will be executed everytime and all services will be registered again? – fingers10 Aug 11 '20 at 00:28
  • Yes, at which point you'd read state from wherever you persisted it too. – Peter Morris Aug 11 '20 at 07:34