skip to Main Content

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


  1. import React, { useEffect, useState } from 'react'
    
    const Component = () => {
      const [questions, setQuestions] = useState<any>()
      const [question, setQuestion] = useState<string>()
      const [answers, setAnswers] = useState<[]>()
    
      useEffect(() => {
        fetch('/...')
          .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>
        </>
      )
    }
    
    export default Component
    
    Login or Signup to reply.
  2. try to set values for states like empty string and empty array.

    const [questions, setQuestions] = useState<any>("")
    const [question, setQuestion] = useState<string>("")
    const [answers, setAnswers] = useState<[]>([])
    

    When app loads it try to access state value of state, which is not set yet by useEffect and in Your case is undefined.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search