4
this.state = {foo : [{x:20,y:40},{x:55,y:10},{x:8,y:90},{x:0,y:150}]};//state
this.state.foo[2].x = 80;//change state

I need to update index 2 of foo in x property. but with setState. how I can do this?

0

1 Answer 1

3

You could do the following, which would avoid the need for a third-party library while also maintaining immutability in your state update:

// Clone the foo list from state
const foo = this.state.foo.map(item => ({ ...item }));

// Update element in cloned list
foo[2].x = 80;

// Update state with cloned list
this.setState({ foo });
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, but you need to wrap {...item} in parentheses.

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.