Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React not setting state immediately

I have a function where if the user gets the correct answer I update the score

firstly is this the right way to do this: this.setState({ score: this.state.score + 1 } I figure it may not be

Secondly, this function increments the score but not the first time for some reason. I appreciate this is only one function so hard to follow but can answer questions people have on the code:

countScore(enteredValue) {
    const { quizData, possibleAnswerTotal} = this.props;
    const { score, correctlyEnteredAnswers } = this.state;
    let index;
    let submittedValue;
    let toNum;
    submittedValue = enteredValue.toLowerCase();
    if (quizData.includes(submittedValue)) {
      correctlyEnteredAnswers.push(submittedValue);
      this.setState({ score: this.state.score + 1 }) //this works just not the first time
      index = quizData.indexOf(submittedValue);
      quizData.splice(index, 1);
      console.log(quizData, 'qd');
      this.changeBackgroundColorCorrectAnswer();
      toNum = Number(possibleAnswerTotal)
      console.log(score, 'scoressss');
      if (score != 0 && score === toNum) {
        console.log('here');
        this.quizCompleted();
      }
    } else {
      this.changeBackgroundColorInCorrectAnswer();
    }
  }
like image 845
The Walrus Avatar asked Sep 16 '26 17:09

The Walrus


1 Answers

By design, setState is asynchronous - this allows for optimizations such as batched updates, delaying updates to components that are off screen, and so on. If you want to ensure some code gets called only after the state has actually been updated, you can pass a callback as the second argument. For similar reasons, it's also recommended that you use the updater function form if you're relying on the state/props in your call to setState.

this.setState((prevState, props) => {
    return {
        score: prevState.score + 1
    };
}, () => {
    console.log("state updated");
});
like image 159
Joe Clay Avatar answered Sep 19 '26 07:09

Joe Clay