简体   繁体   中英

I'm getting "TypeError: Cannot read properties of undefined(reading: 0)" in React

I am trying to make a quiz app using React (using API).

API Link:- ( https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple )

But I am getting an error in the console saying the following: enter image description here

This is my code:

import React from 'react';
import './App.css';

function App() {
  const [answer,setAnswer]= React.useState([])
  React.useEffect(()=>{
      fetch("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple")
      .then((res)=> res.json())
      .then(data => setAnswer(data.results[3]))
    }, [])

  return (
    
    <div className="App">
      <h1>{answer.question}</h1>
      <h2>{answer.incorrect_answers[0]}</h2>
      <h2>{answer.correct_answer}</h2>

    </div>
  );
}

export default App;

Error is in the line 24:1 which is:

<h2>{answer.incorrect_answers[0]}</h2>

When I am using without the index there is no error, instead the entire array of incorrect_answers is being printed but the moment I enter the index and refresh the error show up.

But if I don't refresh and just save the file in my VS Code it is automatically updating in my browser. The moment I refresh it shows up with the error.

Kindly help me in this, I am struck here for a very long time now.

PS: Don't suggest Async,Await method.

You can try the following code

{answer.incorrect_answers && answer.incorrect_answers[0]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM