React mixin for caching state in sessionStorage across mounts.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.