Reputation: 10035
From what I've read, redux uses Object.assign
or the spread operator to make a shallow copy of the data, but how does that make sense? I thought the whole point of it was to make a deep copy of the data that is dispatched so that if the data is changed outside the store, it won't change what's in the store also. if it were a shallow copy, then the data would be linked, which causes issues with the data changing what's in the store even without a dispatch, correct?
In the example below, if action.data were only shallowly copied, then if that data were changed from wherever it came from, it would change what's in the store, even without the dispatch right?
const activePokemon = (state = {}, action) => {
switch (action.type) {
case 'ADD_ACTIVE_POKEMON':
return {
...state,
...action.data
}
default:
return state
}
}
Upvotes: 2
Views: 1562
Reputation: 5944
If you are following the Three Principles of redux
, then you won't worry about changes outside the store.
The only way to change the state is to emit an action, an object describing what happened.
If the changes outside the store are intended to modify the state, dispatch
should be used instead. In addition to update of the state, dispatch
also notifies every subscriber of the store about the changes.
And once you 'linked' some data to the state, the data should not be changed, since it is a part of the state, and..
State is read-only
Edit: about making a copy
In the documentation of reducers(read it again for details!), redux
only requires our reducers to stay pure. If the new state is different, the reducer must create new object, and making a copy is a way to describe the unchanged part.
We are not always making a copy to describe the new state. return {}
can be used to clear all state properties, when there are only a few properties to keep, we can specify unchanged properties instead of copying:
return {
unchangedProp0: state.unchangedProp0,
unchangedProp1: state.unchangedProp1,
...newData
}
Upvotes: 1