I’m trying to display all the questions from this data set however it’s only working sometimes and then other times I receive ‘questions is undefined’.
Why am I receiving this error?
const [questions, setQuestions] = useState<any>();
const [question, setQuestion] = useState<string>()
const [answers, setAnswers] = useState<[]>()
useEffect(() => {
fetch("/environment_questions")
.then((response) => response.json())
.then((data) => setQuestions(data));
}, []);
useEffect(() => {
if (questions.length > 0) {
for (let i = 0, l = questions.length; i < l; i++) {
setQuestion(questions[i].question)
setAnswers(questions[i].answers)
}
}
}, [questions])
return (
<p>{JSON.stringify(question)}</p>
<p>{JSON.stringify(answers)}</p>
)
}
Data I’m trying to access:
[{"id":1,"question":"...":[{"id":1,"answer":"..."},{"id":2,"answer":"..."}]},{"id":2,"question":"...","answers":[{"id":1,"answer":""},{"id":2,"answer":""},{"id":3,"answer":""}]} ...}]
2
Answers
try to set values for states like empty string and empty array.
When app loads it try to access state value of state, which is not set yet by useEffect and in Your case is undefined.