0

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.

1
  • Did you have any luck with my answer. Commented Apr 4, 2018 at 20:12

1 Answer 1

1

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()

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

9 Comments

Thanks for the reply. You're assigning an empty object to employee(s) before calling setState. I can't understand how this might work.
Sorry, I've updated the example. The point is you update some properties, then pass the updated copy to setState.
Sorry, for the late follow up. The problem is that the spread operator doesn't make a "deep" copy of the object. Here is a nice explanation of what I mean bambielli.com/til/2017-01-29-spread-operator-deep-copy My point was to use the initialState to not have to reassign each property manually
I see. Are you able to maybe change the makeup of the state object so you don't have to jump through these hoops?
Yeah. I read somewhere that fb suggests keeping the state flat but that trows complexity to other parts of the app. I just wanna know what's the best practice of handling nested state in React without using Redux or smth.
|

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.