Using LocalStorage with React?
The .setItem()
local storage function returns undefined
. You need to perform the local storage update and then return the new state object:
switchoff: function(){
localStorage.setItem('state', 'off');
this.setState({lights: 'off'});
},
Here is just another Example:
import React from 'react'
class App extends React.Component {
constructor(props) {
super(props);
var storedClicks = 0;
if (localStorage.getItem('clicks')) {
storedClicks = parseInt(localStorage.getItem('clicks'));
}
this.state = {
clicks: storedClicks,
};
this.click = this.click.bind(this);
}
click() {
var newclick = this.state.clicks + 1;
this.setState({clicks: newclick});
// Set it
localStorage.setItem('clicks', newclick);
}
render() {
return (
<div>
<h2>Click the button a few times and refresh page</h2>
<button onClick={this.click}>Click me</button> Counter {this.state.clicks}
</div>
);
}
}
export default App;
These 4 methods u can use.
// setter
localStorage.setItem('myData', data);
// getter
localStorage.getItem('myData');
// remove
localStorage.removeItem('myData');
// remove all
localStorage.clear();