'What is correct way to update nested objects in redux
I was reading this redux documentation . https://redux.js.org/usage/structuring-reducers/immutable-update-patterns .
please see the below code
function insertItem(array, action) {
return [
...array.slice(0, action.index),
action.item,
...array.slice(action.index)
]
}
they are using the slice method for updating the state and but what if state looks like below
const state = [{name:"x1",obj:{}},{name:"x2",obj:{}},{name:"x3",obj:{}}];
let y = {...state.slice(1)};
console.log(state[1]['obj'] === y[0]['obj']) // true
console.log(state[2]['obj'] === y[1]['obj']) // true
is it ok to update states in this way . or it is wrong as we are updating state directly we can see in console.log our new state still point to old state nested object references . or copying old state refrence while making new state is fine . does not cause any issue .
I see one question on stackoveflow . I commented on the solution . that was also refrencing the old state .
Adding Object to nested array in react-redux
let state = {
items : {
deepItem :[1, 2, 2],
reallyDeepItem: {
a : [1,2,3],
b : ['a', 'c']
}
}
};
let x = {
...state,
items : {
...state.items,
deepItem : state.items.deepItem.concat(3)
}
}
console.log(x.items === state.items) // false
console.log(x.items.reallyDeepItem === state.items.reallyDeepItem) // true (still pointing the old reference )
console.log(x.items.deepItem === state.items.deepItem) //false
I know we can use Immerjs and reduxtool kit but i want to understand how to update immutable state correctly .
Solution 1:[1]
this link explain this question . https://catwolf.org/qs?id=3f201d2d-da9f-4019-88ab-566a765b7835&x=y
Common Redux misconception: you need to deeply clone the state. Reality: if something inside doesn't change, keep its reference the same! below is doc link. https://redux.js.org/faq/performance#do-i-have-to-deep-clone-my-state-in-a-reducer-isnt-copying-my-state-going-to-be-slow
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user9083933 |
