0

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.

RogerDore
  • 93
  • 1
  • 7
  • 1
    Clearly, `this.state.choosenDriver.cars` has no own properties so you don't see `alert(ix)` for the first time. – dfsq Oct 18 '15 at 09:47
  • @dfsq: Sounds like an answer. :-) (Except it wouldn't have to be an *own* property, inherited ones would also show up. *Enumerable*, yes, but *own*, no.) – T.J. Crowder Oct 18 '15 at 09:49
  • @ Roger: If `cars` is an array, note that that's almost certainly not now you should loop through its entries. [My answer here](http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript/9329476#9329476) gives you a list of ways, but either use `forEach` or similar, or (at least) add a `hasOwnProperty` check inside the loop. – T.J. Crowder Oct 18 '15 at 09:51
  • But in the functions first line : this.setState({choosenDriver: this.state.drivers[i]}); its gets it values. Or am I wrong? – RogerDore Oct 18 '15 at 09:51
  • cars is an Array, I will look at your link! But you dont Think its a good idea to loop through the [cars] at this Place in the code? Im not sure where else to do it, everytime choosenDriver Changes, that is where i need to do something with the cars. – RogerDore Oct 18 '15 at 09:54

0 Answers0