1

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?

1 Answer 1

2

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>
}}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer, though I'm looking to display the values inside a radio button :D
The answer is good but main thing missing is key to the p element. If you don’t add key then only one p element will be rendered. A key can be unique id of each object from data or index. But preferably use unique id as key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.