0
votes

I'm becoming a bit confused about how to update state in NgRx reducer, here is the question.

Say I have a state

{
   xxx: num
   yyy: classtpe
   ... 
   data: Data[]
}

If I have an action to add a Data item to the list.

I know I can't call data.push() because that just update the array but data pointing to same array so in the reducer I have

state.data = cloneDeep(state.data)
state.data.push(newdata)

so state.data now is different from previous one because they are 2 individual arrays.

my question is, can I return state directly now? If yes then the old and new states point to same variable, they have exactally same members except data.

The other way is, return a brand new state like

    return Object.assign({}, state, {
      data: [...state.data, newdata]
    })

or

const newstate = cloneDeep(state)
newstate.data.push(new data)
return newstate

this way new and old state are totally different.

I think it's actually related to how difference is checked in NgRx? first way they need to go through each memeber, if any member is different then the state is differnet?

2nd way the 2 states are different, but all the memebers need to be checked to see if contents are same.

1

1 Answers

0
votes

I would recommend you to use ngrx-immer, https://github.com/timdeschryver/ngrx-immer

It's an Immer wrapper around ngrx reducers so you can update all of the state mutably, and it will do the rest for you. Immer is also used in the redux-toolkit to make it simple to update state.