-
-
Save SirSerje/f2bae4c160a2efb345e3e8beafc7f1b4 to your computer and use it in GitHub Desktop.
A higher-order component to access localStorage
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 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