Home > OS >  trying to call api with multiple objects react JS
trying to call api with multiple objects react JS

Time:12-29

I'm trying to call a specific object within an api but it returns error ...

calling the first one works but when i call the second objects it returns error

here's the code Api link : https://opentdb.com/api.php?amount=3&difficulty=easy&type=multiple

const [quiz,setQuiz] = React.useState([""])

React.useEffect(() => {
  async function getQuiz() {
    const res = await fetch(
      "https://opentdb.com/api.php?amount=3&difficulty=easy&type=multiple"
    );
    const data = await res.json();
    setQuiz(data.results);
  }
  getQuiz();
});
return (
  <QuizPage
    questionOne={quiz[0].question} //this works //
    questionsTwo={quiz[1].question} //this not //
  />
);

I tried to create separate states but it did not work either i tried to create a seperate state and calling a second object but that didnt work either, i also tried to map over it and still didnt work, i tried many other methods to call api but still no solutions and i get this error in the console ncaught TypeError Cannot read properties of undefined reading 'question, Consider adding an error boundary to your tree to customize error handling behavior, logCapturedError

CodePudding user response:

const [quiz,setQuiz] = React.useState([""])

Your initial sate has only one element, so quiz[1] is undefined, and quiz[1].question will throw an error. You will need to check for the case where you don't have data and either show nothing, or show some loading screen. For example:

const [quiz,setQuiz] = React.useState(null)
// ...

if (!quiz) {
  return <div>Loading...</div>
} else {
  return (
    <QuizPage
      questionOne={quiz[0].question}
      questionsTwo={quiz[1].question}
    />
  );
}
  • Related