Skip to content

Instantly share code, notes, and snippets.

@mk0x9
Created November 8, 2017 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mk0x9/3cad52fd8ca027990467cf2446916305 to your computer and use it in GitHub Desktop.
Save mk0x9/3cad52fd8ca027990467cf2446916305 to your computer and use it in GitHub Desktop.
import _set from 'lodash/fp/set';
import _get from 'lodash/fp/get';
const LOCAL_STORAGE_WORKS = (() => {
const key = '__test_local_storage__';
try {
localStorage.setItem(key, key);
localStorage.removeItem(key);
return true;
} catch(e) {
return false;
}
})();
let cache = {};
const lsKey = 'cached-state';
function set(prop, value) {
if (LOCAL_STORAGE_WORKS === true) {
const settings = JSON.parse(localStorage.getItem(lsKey));
localStorage.setItem(lsKey, JSON.stringify(
_set(prop, value, settings)
));
} else {
cache = _set(prop, value, cache);
}
}
function get(prop) {
if (LOCAL_STORAGE_WORKS === true) {
const settings = JSON.parse(localStorage.getItem(lsKey));
return _get(prop, settings);
} else {
return _get(prop, cache);
}
}
export default function withCachedState(WrappedComponent, prefix) {
const klass = class extends WrappedComponent {
constructor(props) {
super(props);
this.state = {
...this.state,
cached: get(prefix) || this.state.cached
};
}
componentWillUpdate(nextProps, nextState) {
super.componentWillUpdate(nextProps, nextState);
set(prefix, nextState.cached);
}
};
klass.displayName = `${withCachedState.name}(${WrappedComponent.displayName})`;
return klass;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment