Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
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 Respostas
Responde à pergunta

0

You can try below code

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda