Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Last active March 4, 2024 21:01
Show Gist options
  • Save treyhuffine/34d71b54194a83d8b8a384b8eaa2b9e4 to your computer and use it in GitHub Desktop.
Save treyhuffine/34d71b54194a83d8b8a384b8eaa2b9e4 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