Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

203
Views
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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can try below code

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!