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":""}]} ...}]