ik00ma
ik00ma

Reputation: 432

How to handle React.js nested state?

I need to have a nested state in my main component. I came up with having the initialState which I was going to use for the reset feature.

constructor() {
  ...
  this.initialState = {
    ...
    employees: {
      manager: {
        name: 'Andrew',
        age: 27
      }
      developer: {
        name: 'David'
        age: 32
      }
    }
    ...
  };

  this.state = this.initialState;

But it doesn't work with React. As setState can't handle nested properties and both this.state and this.initialState are just references to the same object. I've tried spread operator, Object.assign and finally came across a immutability-helper

But I still can't understand how to set state in the constructor and how to "reset" the employees part of the state later on.

Other properties of state are flat.

Upvotes: 0

Views: 1080

Answers (1)

Paul McLoughlin
Paul McLoughlin

Reputation: 2289

To set the initial state, just use

this.state = {
    employees:
      manager: {
        name: 'Andrew',
        age: 27
      }
      developer: {
        name: 'David'
        age: 32
      }
}

Then use setState to make changes to the state object.

To make changes to nested objects inside the state, We take advantage of object destructuring, by creating a new object which is a copy of the nested employee object. We can make changes to the newly created employee object, then save that using this.setState

resetEmployee() {
    let employee = {...this.state.employee}
    employee.someProperty = someNewValue 
    this.setState({employee}) 
}

You could properly abstract this even further, but the example serves the purpose of updating nested objects within the state.

For a deep copy we would look to JSON.stringify()

Upvotes: 1

Related Questions