0

I am trying to figure out why I have a function that can not read in a value from a useState hook. I now that the useState value of "questionIndex" is updating properly in my verifyAnswer function, but I cannot determine why the function "renderQuestion" is not aware that the value of questionIndex is updating.

I do not receive any error messages, and I have conosole logged the outputs. The questionIndex updates as expected but the renderQuestion function doesn't at all.

Earlier I was trying to use useEffect and it was working fine, but the code was kind of messy. Now I'm second guessing my understanding of React in general because the code seems like it should work just fine, and I am lost trying to track down the solution.

Code:

const [questionIndex, setQuestionIndex] = useState(0)

function renderQuestion() {
    console.log(`questionIndex from render question function is : ${questionIndex}`)
        setWordToTranslate(Data[questionIndex].word);
        setAnswer(Data[questionIndex].translation)
}


function verifyAnswer(value) {
    if (value === answer) {
        console.log("answer is correct!");
        if (questionIndex < questionsLength) {
            setQuestionIndex(questionIndex + 1)
            renderQuestion()
        }
    }
}


function handleInputChange(event) {
    const {value} = event.target;

    setUserInput(value);

    verifyAnswer(value);
}
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Robert
  • 176
  • 1
  • 12

1 Answers1

0

setState is asynchronous.

I think you should handle the renderQuestion in a useEffect

const [questionIndex, setQuestionIndex] = useState(0)

function renderQuestion() {
    console.log(`questionIndex from render question function is : ${questionIndex}`)
        setWordToTranslate(Data[questionIndex].word);
        setAnswer(Data[questionIndex].translation)
}

useEffect(() => {
   renderQuestion()
}, [questionIndex])

function verifyAnswer(value) {
    if (value === answer) {
        console.log("answer is correct!");
        if (questionIndex < questionsLength) {
            setQuestionIndex(questionIndex + 1)
        }
    }
}


function handleInputChange(event) {
    const {value} = event.target;

    setUserInput(value);

    verifyAnswer(value);
}
HichamELBSI
  • 1,712
  • 13
  • 19