Have a look at this simple function:
handleEventClick(i){
this.setState({choosenDriver: this.state.drivers[i]});
alert(i);
for (let ix in this.state.choosenDriver.cars) {
alert(ix);
}
}
What I would expect to happen is that both alert(i)
and alert(ix)
should get triggered when I click.
For some reason alert(ix)
does not fire on the first click but works as it should from the second click. alert(i)
however works as it should.
Can someone explain this? Thank you!
Update:
Than you both for answering. Im sure that you have already explained the problem but I still dont understand.
Now I try this:
handleEventClick(i){
this.setState({choosenDriver: this.state.drivers[i]});
let a = this.state.choosenDriver.cars;
Array.prototype.forEach.call(a, function(child) {
// Do something with `child`
alert(child);
});
And on the first click it generates the following error:
Uncaught TypeError: Array.prototype.forEach called on null or undefined
But I DO define choosenDriver on the first line BEFORE looping through it so I dont understand why I get this error.