1

I have an array of components which each have component details and I'm trying to update a detail for a component.

I know I can do this

this.setState({
    component: {
       ...this.state.component,
       [var]: value
    }
});

but I need to be able to do this

this.setState({
    component[key]: {
       ...this.state.component[key],
       [key2]: value
    }
});

which fails. How can I modify a sub array without modifying state and replacing the whole thing?

1 Answer 1

3

You would need to update the nested data within component state as well

this.setState({
    component: {
       ...this.state.component,
       [key]: {
          ...this.state.component[key],
          [key2]: value
       }
    }
});

However when you are updating state based in previous state, it preferable to use callback method to update state

this.setState(prevState: ({
    component: {
       ...prevState.component,
       [key]: {
          ...prevState.component[key],
          [key2]: value
       }
    }
}));
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.