0

I'm trying to use prototypes to make looking up data from a deeply nested object easier. The issue is, when I use lodash's cloneDeep function the prototype chain is broken ( I'm pretty sure ). I'm using the cloneDeep function to make sure not to mutate the state directly.

Before waisting anyone's time with some of the code from the project, is this an okay practice? Is it correct to do something the following or should prototypes be avoided when storing objects in state?

const parent = { a: { b: { c: null }}}
const child = Object.create(parent)
parent.a.b.c = child

this.setState({ parent }) 

Thank you in advance for the help :)

Chris O
  • 41
  • 7

1 Answers1

0

I would second-take any deeply nested abstraction used as state. Your state should be as flat as possible. Nesting makes for really buggy code, and updating becomes a monumental task.

constructor() {
    this.state = {foo: 'bar', a: 1, b: 2}
}

handleEvent(event) {
    this.setState({ ...this.state, foo: event.target.value })
}

render() {
    const { foo, a, b } = this.state
    // ...
}

This isn't really the direction React is moving though. I would suggest having a look at the latest release notes.

taystack
  • 2,004
  • 18
  • 17