5

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

1 Answer 1

9

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.