Here is the code by which I try to update the state values. I wasn't able to figure out why my state didn't get updated. I added all the respective console values at each line of code.
handleFilter=(event)=>
{
console.log(this.state.answerStatus) // Before update 'all'
let val= event.target.value === "answered";
console.log(val); // true or false
this.setState({answerStatus:val});
console.log(this.state.answerStatus); // 'all'
}
In React setState
is asynchronous, which means that the sate value won't be modified right after you call setState
and that is why you get the old values from the console.log.
Why is setState in reactjs Async instead of Sync?
handleFilter = (event) => {
console.log(this.state.answerStatus) // Before update 'all'
let val= event.target.value === "answered";
console.log(val); // true or false
this.setState({answerStatus:val}, () => {
console.log(this.state.answerStatus);
});
}