Question

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.

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top