-
Notifications
You must be signed in to change notification settings - Fork 76
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Anti-pattern: Mutating state and action payload #9
Comments
Thanks @gaearon for the detailed instructions, I have revised the code according and pushed the bits. Major changes include:
In the future I might as well just use immutablejs to maintain the immutability (which comes with better fool-proof capability). After the rewrite, redux-devtools is confirmed to working as expected! @gaearon would you mind reviewing the revision again? thanks. |
Everything looks good now! Thanks for addressing all of these so quickly. |
Thanks for using Redux!
This example has a significant problem: its reducers aren't pure. For example,
state.products
is mutated on this line:This goes against how Redux works: you should always return new state instead of mutating the state passed by Redux.
Another anti-pattern is above it:
It has two problems:
action.product
is mutated (product.quantity++
). The action payload should never be mutated as this destroys the history.action.product
is one of the items insidestate.products
. This is not currently documented (note to me!), but it's also an anti-pattern. You should never rely on something insideaction
being the same object as something in your state. This is becauseaction
is meant to be a description. It can be serialized, and deserialized again, and your reducers should work exactly the same.When you feel like you want to pass objects like
product
in anaction
, it's a sign you really want to store an ID map, and passproductId
inside the action. See Redux TodoMVC reducer as an example of that:Note that it never writes to the state, and it also never relies on a particular object being equal to something inside the state.
These anti-patterns are likely the reason DevTools didn't work for you (6998c46). They assume the reducers are pure.
We'll make sure to document these anti-patterns and how to avoid them.
Thanks again!
The text was updated successfully, but these errors were encountered: