-1

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'
  }

0

2 Answers 2

2

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?

React Docs

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);
    });
    
  }
1

State updates are async.

To see updated value after setState, use second argument which takes a callback function and issue console log over there.

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)
  );
};

Not the answer you're looking for? Browse other questions tagged or ask your own question.