Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React mixin for caching state in sessionStorage across mounts.
var StateCacheMixin = function(key) {
if (!Modernizr.sessionstorage) {
return {};
}
return {
componentWillMount: function() {
var prevState = sessionStorage.getItem(key);
if (prevState === null) return;
try {
prevState = JSON.parse(prevState);
}
catch (e) {
return;
}
if (typeof prevState === 'object') {
this.setState(prevState);
}
},
componentWillUnmount: function() {
if (this.state !== undefined) {
sessionStorage.setItem(key, JSON.stringify(this.state));
}
}
};
};
@heyimalex
Copy link
Author

heyimalex commented Oct 14, 2014

Things I don't like: can't use session-stored variables in componentWillMount (as the mixin method apparently gets called after the component), no granularity in choosing which properties to store.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment