Last active
March 26, 2018 12:12
-
-
Save treyhuffine/82ccc94182ea995d20874ed035c5e2a0 to your computer and use it in GitHub Desktop.
A render prop component to access localStorage
This file contains hidden or 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 React from 'react'; | |
class Storage extends React.Component { | |
state = { | |
localStorageAvailable: false, | |
}; | |
componentDidMount() { | |
this.checkLocalStorageExists(); | |
} | |
checkLocalStorageExists() { | |
const testKey = 'test'; | |
try { | |
localStorage.setItem(testKey, testKey); | |
localStorage.removeItem(testKey); | |
this.setState({ localStorageAvailable: true }); | |
} catch(e) { | |
this.setState({ localStorageAvailable: false }); | |
} | |
} | |
load = (key) => { | |
if (this.state.localStorageAvailable) { | |
return localStorage.getItem(key); | |
} | |
return null; | |
} | |
save = (key, data) => { | |
if (this.state.localStorageAvailable) { | |
localStorage.setItem(key, data); | |
} | |
} | |
remove = (key) => { | |
if (this.state.localStorageAvailable) { | |
localStorage.removeItem(key); | |
} | |
} | |
render() { | |
return ( | |
<span> | |
this.props.render({ | |
load: this.load, | |
save: this.save, | |
remove: this.remove, | |
}) | |
</span> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment