-3

I was following a tutorial on YouTube about a quiz app in react version 16. There a few variables in the state and in a function these variables are updated with the help of setState. The values of variables are not being updated. The following in the function which is updating these variables. This function is being called from componentDidMount function.

displayQusetions = (questions = this.state.questions, currentQuestion, nextQuestion, previousQustion) => {
   let { currentQuestionIndex } = this.state;
   if (!isEmpty(this.state.questions)) {
      questions = this.state.questions;
      currentQuestion = questions[currentQuestionIndex];
      nextQuestion = questions[currentQuestionIndex + 1];
      previousQustion = questions[currentQuestionIndex - 1];
      const answer = currentQuestion.answer;

      this.setState({
         currentQuestion,
         nextQuestion,
         previousQustion,
         answer
      })

      console.log(this.state.currentQuestion);
      console.log(this.state.nextQuestion);
      console.log(this.state.previousQustion);
      console.log(this.state.answer);
   }
}

I am new to react. Please help.

Zuckerberg
  • 1,781
  • 2
  • 10
  • 19
Hasan Zubairi
  • 1,037
  • 4
  • 23
  • 57
  • 5
    This question is asked nearly daily, please search. React state updates are asynchronous, so logging right after will only yield state from the current render cycle, use the `setState` callback argument to log the new state. Does this answer your question? [React setState not Updating Immediately](https://stackoverflow.com/questions/38558200/react-setstate-not-updating-immediately) – Drew Reese Apr 08 '20 at 05:41
  • 1
    use `setState`'s second argument as a callback, which will be executed **after** the state is updated – GalAbra Apr 08 '20 at 05:45
  • 1
    Does this answer your question? [React.js, wait for setState to finish before triggering a function?](https://stackoverflow.com/questions/37401635/react-js-wait-for-setstate-to-finish-before-triggering-a-function) – GalAbra Apr 08 '20 at 05:46

1 Answers1

0

you can check the state update value in callback

this.setState({
                currentQuestion,
                nextQuestion,
                previousQustion,
                answer
            },()=>{
            console.log(this.state.currentQuestion);
            console.log(this.state.nextQuestion);
            console.log(this.state.previousQustion);
            console.log(this.state.answer);

})
Narendra Chouhan
  • 2,291
  • 1
  • 15
  • 24