Search code examples
arraysreactjssetstate

ReactJS setState multidimensional array variable keys in sub array


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?


Solution

  • 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
           }
        }
    }));