M
M
Mesuti2021-11-28 20:31:27
JavaScript
Mesuti, 2021-11-28 20:31:27

How is it more convenient to update an object in state through the useState () hook?

Hey!
What is the best way to update object keys using the useState() hook ?

The state has a heavily nested object.
Since the hook replaces the entire object with a new one, now to update only 2 keys I use quite a lot of spread operators to save the previous state and the code looks like this

setState(state => {
    return {
        ...state,
        result: {
            ...state.result,
            voice: {
                ...state.result.voice,
                month3: voice3month
            },
            profit:  {
                ...state.result.profit,
                month3: profit3month
            },
        }
    }
})


Tell me, please, what is the best way to update several keys in multilevel objects?


Thanks for participating!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-11-28
@Mesuti

The easiest way is to use MobX, it's just convenient to work with deep trees there.
useState adheres to the immutable scheme, and there's not much you can do about it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question