Bercovici Adrian
Bercovici Adrian

Reputation: 9360

Keeping state of component after refresh

Hello i am wondering how can you keep state of a component variable in Blazor without using different pages. Lets say i have a Parent page that has a Login component :

Login

 @functions()
   {
   public Action<string>onlogin{get;set;}  //some logic that triggers this event to the parent , ---not important
   }

Main

@if(this.id==string.Empty)
{
<Login onlogin="@((value)=>OnLoginEvent(value))"></Login>
}

@functions()
{
 public string id{get;set;}=string.Empty;
 public void OnLoginEvent(string value)
 {
   this.id=value;
 }

Now as you can see ,the first time i render the Main component and i log in , the id will become be different from string.Empty, and so the Login component will then disappear. However if i refresh the page , i am still back with the login component rendered ,so the id is resetted.

Can i somehow keep the state of a Component variable even after refresh ? In this case i want to keep id from being string.Empty even after refresh?

P.S I do not want to use different pages , and i was thinking as a solution to store the value of id in a service that is injected.Is there any other way?

Upvotes: 1

Views: 4814

Answers (1)

Chris Sainty
Chris Sainty

Reputation: 8521

A service would be a good way to solve your problem, as you've concluded. But another option would be to use the browsers local storage. This would persist your data in a very robust way. You can use a library such as this one BlazoredLocalStorage (Full disclosure, I'm the author).

This method would persist the data outside of a users session though, so, for example, a user could close the browser and come back a day later and the data would still be present. So you would have to manage that. But this is how many SPA applications handle this problem.

Upvotes: 2

Related Questions