Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ngrx store immutable state with an array?

I'm planning to create a large application with Angular 5. I want to use Ngrx too to store the state of my app. But there is one thing I don't understand.

Let's say that I have an object (I don't use classes or interfaces now for simplicity), that represents my state in a Store:

let state = {
    x: 10,
    y: [1, 2, 3]
};

In every article that I read the writers are using Object.assign() to create a copy of the state in a reducer. For example:

...
case SET_X:
    return Object.assign({}, state, {x: 123});
...

But this doesn't create a deep copy of the state. So the y array of the new state is the same as the old one's. This is against the concept of Redux/Ngrx, I think.

So does this mean that I have to use List Immutable.js or something like that for example, and every article is "wrong"? Or am I missing something? I don't think that this would be a very special case.

like image 437
Roland Rácz Avatar asked Jan 02 '23 23:01

Roland Rácz


1 Answers

No you don't have to use Immutable.js (and I wouldn't recommend you to).

If you want to update the array, let say add a value, you should just do it like that:

const state = {
  x: 10,
  y: [1, 2, 3]
};

const newState = {
  ...state,
  y: [...state.y, 4]
}

Here you can notice 2 things:
- Instead of using Object.assign, you can use the spread operator with object
- To keep the immutability with an Array, you have to create a new reference. And you can also just use the spread operator on an Array and then just add a new value for example. If you wanted to add it before and not after: y: [4, ...state.y], if you wanted to remove all the 3 in the array: y: state.y.filter(nb => nb !== 3)

like image 196
maxime1992 Avatar answered Jan 05 '23 16:01

maxime1992