How To Store A State In Localstorage For React?
Solution 1:
You need to pass whatever logic you want to execute post state change as a second argrument to this.setState()
example:
state = {
name: 'Johnny'
}
someMethod = () => {
this.setState({name: 'Tim'})
doSomethingElse(this.state.name) //doSomethingElse receives Johnny
}
I think what you're looking for is
state = {
name: 'Johnny'
}
someMethod = () => {
this.setState({name: 'Tim'}, doSomethingElse(this.state.name))
//doSomethingElse receives Tim
}
See the docs for setState here.
Solution 2:
React tries to batch the setState command. It is more like an asynchronous task. So when you execute this.setState({checkedCheckpoint : true}) it only tells react to set the state of 'checkedCheckpoint' to true but it does not execute that command at that moment. So basically when you are trying to set your localStorage variable it is still the previous state.
Try setting your new state in a variable like this.
onChange (value){
var newState;
const { checkedCheckpoint } = this.stateif (value === 'checkpoint') {
if (checkedCheckpoint) {
newState = false;
console.log(newState);
}
else {
newState = true;
console.log(newState);
}
this.setState({checkedCheckpoint : newState});
localStorage.setObject('checkedCheckpoint', newState);
}
Solution 3:
You need to set it based on the new value not the old one
onChange (value){
const { checkedCheckpoint } = this.stateif (value === 'checkpoint')
{
if (checkedCheckpoint)
{
this.setState({checkedCheckpoint : false})
localStorage.setObject('checkedCheckpoint', false)
console.log(checkedCheckpoint)
}
else
{
this.setState({checkedCheckpoint : true})
localStorage.setObject('checkedCheckpoint', true)
console.log(checkedCheckpoint)
}
}
Solution 4:
Perhaps, you can do something like this:
<Checkbox
checked={this.state.checkedCheckpoint}
onChange={() =>this.setState((prevState) => ({checkedCheckpoint: !prevState.checkedCheckpoint}),
() =>{console.log(this.state.checkedCheckpoint)})}
>
</Checkbox>
Also, the issue with your code was that it doesn't account for the fact that state
in react setState happens asynchronously. As a consequence, it'll always show a previous state while logging.
Post a Comment for "How To Store A State In Localstorage For React?"