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

237
Visualizações
TypeError when Using API in Javascript

I'm trying to make a Trivia Game using Open Trivia DB.
What I want is to display only the questions in the triviaQ constant and I did that. The code works, it does what I want it to do BUT, when I refresh the page sometimes, this error shows up in the console:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'question')
The error points to: question_data.question and underlines the question which doesn't make sense because it is a valid key from the API json. Plus, what confuses me even more is that it still displays the question even if there is an error and the error appears sometimes. Thank you in advance for your time!

Javascript Code:

const api_url = 'https://opentdb.com/api.php?amount=10&difficulty=easy&type=boolean'
const triviaQ = document.getElementById("triviaQuestion")
let question_data = ""

async function display() {
    const response = await fetch(api_url);
    const data = await response.json()
    for (let i = 0; i <= 10; i++) {
        var randNum = Math.floor(Math.random() * 11);
        question_data = data.results[randNum]
        triviaQ.innerHTML = question_data.question
    }
}

display()
about 4 years ago · Juan Pablo Isaza
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