Skip to content

Instantly share code, notes, and snippets.

@heyimalex
Created August 4, 2014 19:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heyimalex/d757c738775fa4b78301 to your computer and use it in GitHub Desktop.
Save heyimalex/d757c738775fa4b78301 to your computer and use it in GitHub Desktop.
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

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