Home > OS >  Passing state as initial value to another state is undefined
Passing state as initial value to another state is undefined

Time:01-09

I'm setting the initial value of correctAnswer state by extracting the data from another. Its giving me undefined. but same value is console logging correctly.

  let refinedAnswer = questions[currentQuestion]?.correct_answer;

  //correct answer for each question
  const [correctAnswer, setCorrectAnswer] = React.useState(refinedAnswer);

 console.log("CORRECT ANS", correctAnswer); //undefined
 console.log("CORRECT ANS", questions[currentQuestion]?.correct_answer); //value

CodePudding user response:

You need to use the value in useEffect. For example:

useEffect(() => setCorrectAnswer(refinedAnswer), [refinedAnswer])

CodePudding user response:

You need to add the useEffect hook to update the state when "undefined" turns into a value. Then the component is rerendered with the correct value:

 React.useEffect(() => {
    setCorrectAnswer(refinedAnswer);
  }, [refinedAnswer]);

  console.log("CORRECT ANS", correctAnswer);

https://codesandbox.io/s/exciting-sanne-qr0cg?file=/src/App.js

  •  Tags:  
  • Related