Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array list in Redux state

This is a question about state in Redux js. I have an array list in the state:

{
  list: list
}

According to Redux document, I should not modify the state in the reducer. I want to append a new item to the list. Should I clone the list, or simply append the new item to the list:

let newList = state.list;
newList.push(newItem);
return {
  list: newList
}

The above code actually modify the original state, because the newList is the same list as "state.list". Is this an OK practice, or should I use immutableJS to clone the list?

like image 716
JustWonder Avatar asked Dec 10 '22 19:12

JustWonder


1 Answers

You are mutating the list here and giving back the same reference. I believe something like below should make a new copy

return { list: [...state.list, newItem] }

It's not mandatory to use immutableJS. but you need to make sure not to mutate the state.

take a look at deep-freeze library to make sure that your state is not being edited.

this video from Dan (creator of redux) should help as well

like image 101
Qusai Jouda Avatar answered Feb 24 '23 04:02

Qusai Jouda