setTimeout in react setState

DaveGuras picture DaveGuras · Jun 25, 2018 · Viewed 15.9k times · Source
this.setState(prevState => ({
    score:            prevState.score + 10,
    rightAnswers:     prevState.rightAnswers + 1,
    currentQuestion:  setTimeout(() => {
      prevState.currentQuestion + 1
    }, 2000)
    }))
  }

On button click I change the state. My goal is to have a delay in currentQuestion state change, during which I want to show certain status messages, yet I want to update the score right away without delays.

What's the proper way to do that?

PS: This variant doesn't work, it's for the overall representation of what I want to do.

Thanks.

Answer

Chase DeAnda picture Chase DeAnda · Jun 25, 2018

You can do this multiple ways:

1) Make two calls to setState. React will batch any concurrent calls to setState into one batch update, so something like this is perfectly fine:

this.setState( prevState => ({
  score: prevState.score + 10,
  rightAnswers: prevState.rightAnswers + 1
}));

setTimeout( () => {
  this.setState( prevState => ({
    currentQuestion: prevState.currentQuestion + 1
  }));
}, 2000);

2) You can use the setState callback to update state after your first call is finished:

this.setState(prevState => ({
  score:            prevState.score + 10,
  rightAnswers:     prevState.rightAnswers + 1
}), () => {
  setTimeout( () => {
      this.setState( prevState => ({
      currentQuestion: prevState.currentQuestion + 1
    }));
  }, 2000);
});