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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With