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

◇◆丶佛笑我妖孽 提交于 2021-02-10 23:17:32

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/63347056/how-to-persist-value-in-a-singleton-state-container-in-blazor-web-assembly-on-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!