React counter state is not updating correctly

Viewed 45

I have the following code. The user clicks a button (answer to quiz question), then it is saved into the myQuiz.userSelection. With this logic, when questionCounter reaches 10, myQuiz should be logged to the console, but it does not happen.

The console logs initial counter: 0 updatecounter: 0 after the first click. The next button click provides initial counter: 1 updatecounter: 1

I'm not quite sure what the issue is here, I hope I can be pointed in the right direction. Initially I thought it might be due to the fact setState() is Async, but I'm not sure if this is the issue.

   let [myQuiz, setMyQuiz] = useState([{
        question: 'What is your favorite color',
        correct_answer: 'green',
        incorrect_answers: ['red','blue','white'],
        userSelection: '',
        allPossibleAnswers:['red','blue','white','green'],
        key: randomKey()
     }])
     let [questionCounter, setQuestionCounter] = useState(0)

    //Logic here to fetch from Quiz API, set myQuiz to an array of 10 objects

    function userClickAnswer(e){
        console.log(`initial counter: ${questionCounter}`)
        setMyQuiz(prevMyQuiz =>{
            let newQuiz= prevMyQuiz.map(item=>{
                return {...item}
            })
            newQuiz[questionCounter].userSelection = e.target.innerHTML
            setQuestionCounter(prevQuestionCounter=>{
                let counter = prevQuestionCounter + 1
                if(questionCounter === 10){
                    console.log(myQuiz)
                    //check how many user answered correctly and update UI
                    let totalCorrect = checkAnswers()
                    setCorrectCounter(totalCorrect)
                    setCurrentStage('result')
                }
                return counter
            })
            return newQuiz
        })
        console.log(`updated counter: ${questionCounter}`)
    }

0 Answers
Related