This is a small utility that will help you solve your applications data persistence needs.
At the heart this is a higher order component which hooks itself to the Component that is wrapped in it.
You have a component with an implementation like this:
import React, { Component } from 'react';
class SomeComponent extends Component {
state = {
tick: 1,
tock: 1,
}
increaseStateCount = (keyName) => {
this.setState({
[keyName]: this.state[keyName] + 1,
});
}
render() {
const { tick, tock } = this.state;
return (
<div>
<div
onClick={this.increaseStateCount.bind(this, 'tick')}
>
Tick is {tick}
</div>
<div
onClick={this.increaseStateCount.bind(this, 'tock')}
>
Tock is {tock}
</div>
</div>
);
}
}
export default SomeComponent;
You can quickly add persistence to the state by following 4 steps:
- Import
withLocalStorage
and wrap it on your component.
import withLocalStorage from 'react-localstorage-sync';
...
SomeComponent = withLocalStorage(SomeComponent);
- Tell which state keys to persist in the localStorage and under what namespace
SomeComponent.localStorageNamespace = 'SomeComponent';
SomeComponent.localStorageKeys = ['tick', 'tock'];
- Get saved state from localStorage when component mounts.
componentDidMount() {
this.setState(this.props.getStateFromLocalStorage(this));
}
- Dance. 👯👯♂️
import React, { Component } from 'react';
import withLocalStorage from 'react-localstorage-sync';
class SomeComponent extends Component {
state = {
tick: 1,
tock: 1,
}
componentDidMount() {
this.setState(this.props.getStateFromLocalStorage(this));
}
increaseStateCount = (keyName) => {
this.setState({
[keyName]: this.state[keyName] + 1,
});
}
render() {
const { tick, tock } = this.state;
return (
<div>
<div
onClick={this.increaseStateCount.bind(this, 'tick')}
>
Tick is {tick}
</div>
<div
onClick={this.increaseStateCount.bind(this, 'tock')}
>
Tock is {tock}
</div>
</div>
);
}
}
SomeComponent.localStorageKeys = ['tick', 'tock'];
SomeComponent.localStorageNamespace = 'SomeComponent';
SomeComponent = withLocalStorage(SomeComponent);
export default SomeComponent;