Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js: Syncing entire state to localStorage

I’d like to store my app’s state in localStorage. Is there a callback or an event that fires on state change? I would use it to call localStorage.state = JSON.stringify(this.state). Possibly, using 0.5 seconds throttling.

TodoMVC React examples uses localStorage as a storage. However, it defines saving and removing in event handlers such as keydown and click. For my case, doing the same would create a lot of boilerplate.

like image 418
NVI Avatar asked Feb 12 '14 22:02

NVI


People also ask

How do you instantly update state when any changes into the localStorage in React JS?

In react, first load data from localstorage / database and initialize the state. Then update the state in the code as you want. Then listen on state changes to do any task ( In this case save to localstorage )

How do I store state in localStorage?

You can initialize your state by getting the value of local storage. useState hook accept a function as a parameter. Now, when your component would render, it will get the value that is on local storage and assign to your state. But, it would be easier if you would use React Context to manage global values .

Is State a permanent storage in React?

Answer: B is the correct option. In ES6, there are three ways of defining your variables: var, let, and const. 14) What is a state in React? A permanent storage.


1 Answers

In a componentDidUpdate lifecycle method you could serialize the state:

componentDidUpdate: function(prevProps, prevState) {
    localStorage.state = JSON.stringify(this.state);
}

That code will be run each time the component rerenders (which happens with every props or state change).

like image 116
Sophie Alpert Avatar answered Oct 07 '22 01:10

Sophie Alpert