Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Last active March 26, 2018 12:12
Show Gist options
  • Save treyhuffine/82ccc94182ea995d20874ed035c5e2a0 to your computer and use it in GitHub Desktop.
Save treyhuffine/82ccc94182ea995d20874ed035c5e2a0 to your computer and use it in GitHub Desktop.
A render prop component to access localStorage
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