Join the Stack Overflow Community
Stack Overflow is a community of 6.8 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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

share|improve this question
up vote 3 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.