0

I have a for loop which is supposed to loop twice. I want to use the incremented values (1 and 2) to set id. However, it gives me value 3 in both cases.

Here is my code:

for(var i=1; i<=2; i++) { //Add two options by default
  this.setState(prevState => ({ //add option Object with default attributes
    options_array: [...prevState.options_array, { id: i,
                                                  description: '',
                                                  value: null  }], 
  })) 
}

4 Answers4

3

Use let instead of var in for loop.

Satpal
  • 132,252
  • 13
  • 159
  • 168
ND NAVEEN
  • 96
  • 5
  • thank you very much! It did solve the problem. Could you, please, enlighten me on the cause of it? – Umar Adkhamov Jul 23 '19 at 07:19
  • 1
    its because of scope of variable ,where let scope will delete for every loop but var scope remains. – ND NAVEEN Jul 23 '19 at 07:23
  • @UmarAdkhamov https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var –  Jul 23 '19 at 07:23
1

You need to wrap the setState function in a unique closure for different i, otherwise they will share the same reference.

for (var i = 1; i <= 2; i++) { //Add two options by default
    (i => this.setState(prevState => ({ //add option Object with default attributes
        options_array: [...prevState.options_array, {
            id: i,
            description: '',
            value: null
        }],
    })))(i);
}
Hao Wu
  • 17,573
  • 6
  • 28
  • 60
0

You can also try this:

let newArray = [];
for(var i=1; i<=2; i++) { //Add two options by default
newArray.push({ id: i,description: '',value: null  });
}

  this.setState(prevState => ({ //add option Object with default attributes
    options_array: [...prevState.options_array, ...newArray], 
  })) 
Bhawana
  • 372
  • 1
  • 6
0

var objectsArray = [];

for(var i=1; i<=2; i++) {
  objectsArray.push(
    {
      id: i,
      description: '',
      value: null
    }
  )
}

this.setState(prevState => ({
    options_array: [...prevState.options_array, ...objectsArray], 
})) 

Try like this.