Reputation: 3357
I'm using the javascript trivia API to make an application. I'm having issues displaying each of the values of the wrong answer.
So far I have saved them in my state, along with the questions, and the correct answer
componentDidMount() {
axios.get('https://opentdb.com/api.php?amount=50').then(response => {
for (var key in response.data.results) {
console.log(response.data.results[key].question)
this.setState(prevState => ({
questions: [...prevState.questions, response.data.results[key].question],
answers: [...prevState.answers, response.data.results[key].correct_answer],
wrongAnswers: [...prevState.wrongAnswers, response.data.results[key].incorrect_answers]
}));
}
});
}
this works fine, but my issue is that the wrong answers is an array itself, so whenever I display the state
<p>{this.state.wrongAnswers[this.state.random]}</p> // prints array of strings
I get another array, and I can access each element using the dot operator, because I don't know the answers since the questions are chosen randomly.
I want to display the values dynamically using radio buttons. Is there a way to access each element of the nested array and display them dynamically?
Upvotes: 1
Views: 124
Reputation: 113
You can loop through that array and show the wrong answers
{Array.isArray(this.state.wrongAnswers) && this.state.wrongAnswers.map((wrongAnswer, index) => {
<p key={'Key-'+index}>wrongAnswer}</p>
}}
Upvotes: 2