I have a react component where I want to get some data, using componentDidmount to get the data initially:
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];
const answer = [...this.state.answer, response.data.results[key].correct_answer];
const wrongAnswers = [...this.state.wrongAnswers, response.data.results[key].incorrect_answers];
this.setState( prevState => ({
question: question,
answer: answer,
wrongAnswers: wrongAnswers
}));
}
});
}
the problem is that I can't map the answers of wrongAnswers because they are undefined initially
const {wrongAnswers} = this.state;
{wrongAnswers[this.state.random] && this.state.wrongAnswers[this.state.random].map((wrongAnswer, index) => { //this does not display
<p key={'Key-'+index}>here it is= {wrongAnswer}</p>
})}
I tried making some checks to see when gets rendered what
{this.state.wrongAnswers &&
console.log('the state is ' +this.state.wrongAnswers[this.state.random]);
} //this renders undefined initially, then renders an array of the right answers..
what is strange is that, if I just display the state, without performing any operations, it is displayed correctly.
<p>{this.state.question[this.state.random]}</p> // displays the state correctly
<p>{this.state.wrongAnswers[this.state.random]}</p> //displays the state correctly
I suspect, that I can't perform any operations, because it is not loaded initially, but since I put it in componentDidMount, you would suspect, that this problem would not occur?
EDIT:
whenever i put in the conditions for a simply parapragh
{this.state.random !== undefined && this.state.wrongAnswers[this.state.random] !== undefined &&
<p> condition is met </p>
}
it prints out
but when i map the array:
{this.state.random !== undefined && this.state.wrongAnswers[this.state.random] !== undefined && this.state.wrongAnswers[this.state.random].map((wrongAnswer, index) => {
console.log('inside the right method!'); //logs correctly three times like intended but does not print any jsx
<p key={'Key-'+index}>here it is= {wrongAnswer}</p>
})}
nothing is printed out.