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

2

Use let instead of var in for loop.

Satpal
  • 129,808
  • 12
  • 152
  • 166
ND NAVEEN
  • 86
  • 5
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
  • 14,894
  • 4
  • 17
  • 48
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
  • 324
  • 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.