From what I am experiencing so far, it doesn\'t seem like ReactJS updates with the state of localStorage. My code below.
var Frr = React.createClass({
getIni
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;
I have written a post regarding this question with some extra information regarding when you should use localStorage:
https://levbuchel.com/react-localstorage/
Original answer:
Your data is determined and saved by pairs of key and value.
Here is an example of how we can add, get and remove such values:
// Add items
localStorage.setItem("theme", "dark");
localStorage.setItem("zoom", "5");
localStorage.setItem("font", "18");
// Get an item
var userTheme = localStorage.getItem("theme");
// Remove an item
localStorage.removeItem("theme");
localStorage.removeItem("font");
These 4 methods u can use.
// setter
localStorage.setItem('myData', data);
// getter
localStorage.getItem('myData');
// remove
localStorage.removeItem('myData');
// remove all
localStorage.clear();
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'});
},
Use please reactjs-localstorage
import {reactLocalStorage} from 'reactjs-localstorage';
reactLocalStorage.set('var', true);
reactLocalStorage.get('var', true);
reactLocalStorage.setObject('var', {'test': 'test'});
reactLocalStorage.getObject('var');