Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
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 Respuestas
Responde la pregunta

0

You can try below code

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda