Reputation: 15075
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.
Upvotes: 10
Views: 12905
Reputation: 143204
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).
Upvotes: 30