S
S
Sergey2019-07-22 23:29:06
React
Sergey, 2019-07-22 23:29:06

How to correctly and beautifully update states for nested objects in React?

Here, for example, there is such a state:

this.state = {
   parent : { 
       someChild: {
           oneMoreChild: { name: 'Test', another: 'Test2'  }
       }
   }
}

But only a small part of all this is actively changing on the page, the rest is not used.
And, suppose, only these values ​​change too (for example, instead of 'Test2', I need to enter 'Test3')
There are two options, I think:
1. I need to take const {parent} = this.state; iterate through map() or some other loops, that's all, write a new value and store it in this.setState();
2. Place a new entity in state at the first nesting level, which will be used, and work with it without any loops, something like this:
constructor(props) {
    super(props)
    const toState =  {
       parent : { 
           someChild: {
               oneMoreChild: { name: 'Test', another: 'Test2'  }
           }
       }
    }

    const { parent } = toState;
    const {someChild} = parent;
    const {oneMoreChild} = someChild;
    const {name, another} = oneMoreChild;

    this.state = {
       toState,
       name: name,
       another: another,
    }
}

And everywhere after doing set.State({ another: 'Test3'}).
Both of these methods seem wrong to me. Because it can be too deep nesting.
But the data structure in the project, not made by me, goes exactly like this (a bunch of nested data is transmitted through props, but only part of them is used). Completely redoing everything, of course, is not an option, we must work with what we have. Plus React is new technology for me. And how to do it right and beautifully?
In general, is there a more correct and beautiful way, when for an object with a high degree of nesting, you need to enter one value somewhere deep in the states? (for example, instead of 'Test2', I need to enter 'Test3' in parent)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2019-07-22
@miraage

immutability-helper (no matter how cumbersome it may seem, it solves its problem)
Ramda (lensProp/lensPath + set/over)
immer

A
Anton Spirin, 2019-07-22
@rockon404

1. map is a method for transforming data, not for iterating.
2. If only two properties are changeable, then it is not clear why you need to have a complex nested structure at all and keep it in state.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question