Reputation: 4045
I believe that I have been modifying my state for quite some time now. I wanted to do the following and was wondering why it did not work:
case "SAVE_DATA_TO_PERSON" :
let newState = {...state, data: {start: action.payload.start, end: action.payload.end}};
return newState;
I am here creating a new object, take the old state, and add my new data. While it does seem to make a difference, it does not keep the data for long. After firing other actions this is just gone. I wonder why?
This is how I used to do it, and it seems to work:
case "SAVE_DATA_TO_PERSON" :
let newState = state;
newState.audio = {start: action.payload.start, end: action.payload.end};
return newState;
But here, it seems, I am modifying state.
I would just like to know whether my first solution is the correct one, and my second solution here is indeed modifying state.
Upvotes: 0
Views: 439
Reputation: 73928
In the second options you are modifying the state directly.
The reducer should changing state in a React-Redux application without mutate existing state.
Immutability is a requirement of Redux because Redux represents your application state as "frozen object snapshots". With these discrete snapshots, you can save your state, or reverse state, and generally have more "accounting" for all state changes. Ref.
You cloud consider using and immutable utility/library as dot-prop-immutable or Immutable.js
Related article from redux docs:
http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html
Upvotes: 1