Reputation: 6899
I have a state array in my constructor:
constructor(props) {
super(props);
this.state = {myarray: []};
}
Now I want to update the array at a specific subscript.
this.setState({myarray[i]: 'test'});
gives me an unexpected token
error, pointing at the opening bracket [
What is the correct way of doing that?
P.S. Array gets filled dynamically using push
method and only then I attempt to update
Upvotes: 4
Views: 6495
Reputation: 816334
Create a copy of the array:
const newArray = Array.from(this.state.myarray);
update the index:
newArray[i] = 'test';
and update the state
this.setState({myarray: newArray});
You can also use immutable helpers (used to be part of React's addons) to do this more concisely.
Upvotes: 9