Created
November 8, 2017 15:14
-
-
Save mk0x9/3cad52fd8ca027990467cf2446916305 to your computer and use it in GitHub Desktop.
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
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