rishi kilaru
rishi kilaru

Reputation: 35

How to update the state array?

I have a state of the component like this:

constructor(props){
   super(props)
   this.state={
      editableComparatorIndexes: []
   }
}

And i am having trouble updating the state, i need to do something like this:

onEditComparatorClicked(i) {
     this.setState({editableComparatorIndexes[i]:1});
     this.setState(this.state);
}

Upvotes: 1

Views: 1600

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104529

First create a copy of state array then update the value then use setState to update the state value.

By using spread operator:

onEditComparatorClicked(i) {
   let editableComparatorIndexes = [...this.state.editableComparatorIndexes];
   editableComparatorIndexes[i] = 1;
   this.setState({editableComparatorIndexes});
}

Or you can use Array.prototype.slice() also it will also return a new array, like this:

onEditComparatorClicked(i) {
   let editableComparatorIndexes = this.state.editableComparatorIndexes.slice();
   editableComparatorIndexes[i] = 1;
   this.setState({editableComparatorIndexes});
}

Upvotes: 6

Related Questions