Skip to content

Instantly share code, notes, and snippets.

@SirSerje
Forked from treyhuffine/withStorage.js
Created January 22, 2019 07:45
Show Gist options
  • Save SirSerje/f2bae4c160a2efb345e3e8beafc7f1b4 to your computer and use it in GitHub Desktop.
Save SirSerje/f2bae4c160a2efb345e3e8beafc7f1b4 to your computer and use it in GitHub Desktop.
A higher-order component to access localStorage
import React from 'react';
const withStorage = (WrappedComponent) => {
class HOC 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 (
<WrappedComponent
load={this.load}
save={this.save}
remove={this.remove}
{...this.props}
/>
);
}
}
return HOC;
}
export default withStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment