1

I'm trying to build a "Quizz" React app using the (open trivia) API, I got the API and assigned it to my state and I'm able to read part of it but when I'm trying to read an array inside the object API I get an error, can you please tell me what I'm doing wrong and how to deal with this in the future. This is my App component:

function App(){
    const [quizz,setQuizz] = React.useState([])
    const [data,setData] = React.useState({
        quizzOn: true
    })
     React.useEffect(()=>{
         fetch("https://opentdb.com/api.php?amount=5&type=multiple").
        then(res => res.json()).
        then(apiData => {
            dataSetter(apiData)
        })},[])
     function dataSetter(obj){
         setQuizz(obj)
         
     }
     function toggle(){
         setData(prev => ({quizzOn:!prev.quizzOn}))
         };
         
    return(
        <div>
        {data.quizzOn && <StartFront onClick={toggle} arr={quizz ? quizz : []}/>}
        {!data.quizzOn &&<Quizz arr={quizz}/>}
        </div>
    )
}

and this is my Quizz component in which I'm trying to read the data:

function Quizz(props){
   const data = props.arr.results
   
   return(
        <div>
        <p>{data ? JSON.stringify(data) : "error"}</p>
        </div>
    )
}

This is working but anything I try after "results" give an error like: props.arr.results[0].question

or:

const data = props.arr.results.map(obj => {
  return <p>{obj.question}</p>})

Finally this the API I'm trying to read:

{
  response_code: 0,
  results: [
    {
      category: "History",
      type: "multiple",
      difficulty: "medium",
      question: "The seed drill was invented by which British inventor?",
      correct_answer: "Jethro Tull",
      incorrect_answers: ["Charles Babbage", "Isaac Newton", "J.J Thomson"],
    },
    {
      category: "Entertainment: Music",
      type: "multiple",
      difficulty: "medium",
      question:
        "Who is the Pink Floyd song &quot;Shine On You Crazy Diamond&quot; written about?",
      correct_answer: "Syd Barrett",
      incorrect_answers: ["John Lennon", "David Gilmour", "Floyd"],
    },
    {
      category: "Entertainment: Television",
      type: "multiple",
      difficulty: "hard",
      question:
        "In &quot;Star Trek&quot;, what is the Klingon delicacy of &quot;gagh&quot; made from?",
      correct_answer: "Serpent worms",
      incorrect_answers: ["Earthworms", "Spaghetti noodles", "Klingworms"],
    },
  ],
};
3
  • 1
    You're passing an empty array as arr on the first render, but then setting it to an object with a results property after the useEffect runs, so on that first render props.arr.results (equivalent to [].results) is undefinedand any further attempt access against it will throw an error. Commented Jun 11, 2022 at 23:11
  • Does this answer your question? Why am i getting and empty array when fetching an api with react hooks? Commented Jun 11, 2022 at 23:12
  • i'm able to read and display props.arr.results but when i'm tring to do anything with the results array here when i'm getting the error Commented Jun 11, 2022 at 23:41

1 Answer 1

0

The first time the component renders, the Quizz component is receiving an empty array, so is an error to do arr.results because arr is not an object

You should validate that you are receiving an object that have a key named results. Something like this:

function Quizz(props){
   const arr = {props};
   const data = props.arr.results
   
   if(!arr.results) return <></>;
   return(
        <div>
        <p>{data ? JSON.stringify(data) : "error"}</p>
        </div>
    )
}

And rename the variable arr would be good too

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.