Reputation: 3357
I have a trivia app application in my React project, where I fetch some data from an API:
question
wrong answers
correct answer
Now I want to make an array of of both the wrong in right answers and map them so the users get all the possible answers in a random order.
I'm having issues creating the array of allAnswers
componentDidMount(){
axios.get('https://opentdb.com/api.php?amount=50').then( response =>{
for(var key in response.data.results){
const question = [...this.state.question, response.data.results[key].question]; // here i put the data into state in each category
const answer = [...this.state.answer, response.data.results[key].correct_answer];
const wrongAnswers = [...this.state.wrongAnswers, response.data.results[key].incorrect_answers];
const allAnswers = [wrongAnswers, answer] // here im trying to collec all possible answers and then later make a handler to check if the given answer was right or wrong
this.setState( prevState => ({
question: question,
answer: answer,
wrongAnswers: wrongAnswers,
allAnswers: allAnswers,
}));
}
});
}
So I save 50 questions and respective answers and wrong answers to not send net work requests all the time.
Then I have made a random counter, that I use to map a random question:
<p>{this.state.question[this.state.random]}</p>
I then map through the array of all the answers to get each answer displayed:
{this.state.random !== undefined && this.state.wrongAnswers[this.state.random] !== undefined && this.state.allAnswers[this.state.random].map((answer, index) => {
console.log(this.state.allAnswers[this.state.random])
return(
<form >
<input type="radio" name="name" value="!!" /> {answer}<br/>
</form>
)
})
})
My issue here is that the array of allAnswers
is just the wrong answers, and I can't find a way to collect all the right and wrong answers in a respective way inside the state.
Upvotes: 0
Views: 43
Reputation: 2849
You can use the spread operator to concat the two arrays.
const answer = [...this.state.answer, response.data.results[key].correct_answer];
const wrongAnswers = [...this.state.wrongAnswers, response.data.results[key].incorrect_answers];
const allAnswers = [...answer, ...wrongAnswers];
This will result in an array that contains the elements of both answer and wrongAnswers.
Hope this helps.
Upvotes: 1