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()