Respond immediately to setting status

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

firstly, this is the correct way to do it: this.setState({ score: this.state.score + 1 }

I suppose it might not be

Second, this feature increases the score, but not the first time for some reason. I appreciate that this is just one function that is so difficult to accomplish, but might answer the questions people have in 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();
    }
  }

      

+3


source to share


2 answers


It setState

is asynchronous by design - it allows you to optimize, for example, batch updates, delay updates to off-screen components, and so on. If you want some code to be called only after the actual state has been updated, you can pass a callback as the second argument. For similar reasons, it is also recommended to use the update function form if you are relying on state / props when called setState

.



this.setState((prevState, props) => {
    return {
        score: prevState.score + 1
    };
}, () => {
    console.log("state updated");
});

      

+2


source


The setState function does not update the state object immediately.



Use the function this.setState

only to reprocess a component. Otherwise, just update the state property directly:this.state.score++

-3


source







All Articles