Skip to content

Make clearer how to not mutate state when you want to. #725

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

Closed
klequis opened this issue Sep 13, 2020 · 2 comments
Closed

Make clearer how to not mutate state when you want to. #725

klequis opened this issue Sep 13, 2020 · 2 comments

Comments

@klequis
Copy link

klequis commented Sep 13, 2020

Here is a suggestion that would make the doc clearer to me. Don't know if that is the majority of the user base. I have only read 80% of the doc so could have missed something, so apology if I did.

I got from the doc that you 'could mutate state or not but not both' and the doc was clear to me on how to mutate state but no on how to not mutate when you didn't want to.

This thread made it clear to me: #242

If I'm understanding things correctly:

mutate state

state.something = something

don't mutate

return newState

I accidentally did (i.e., not mutation0

state = newState

And spent a while trying to figure how why the store was not updating.

hope I got that work but my code is working now

I think a useful addition would be to

  1. make it clearer that in the rare case you don't want to mutate state you just need the return keyword with the new state.
  2. I also didn't see any place that said what would the result will be if you did state = newState, which in my case was the store didn't update.
  3. A third thing I didn't get from the doc was if you could make the mutate vs not mutate choice on a per reducer basis rather than on some larger slice or project level. Making point Create LICENSE #1 clearer would solve this.
@markerikson
Copy link
Collaborator

markerikson commented Sep 13, 2020

Yeah, please feel free to submit PRs to improve any docs phrasing or descriptions you feel aren't clear enough.

In this specific case, state = newState simply points the local function variable state to something else. Immer works by tracking mutations, ie, state.someField = newValue, and also allows returning an entire new result. Pointing a local argument to something else will have no effect.

@markerikson
Copy link
Collaborator

Covered by the new "Writing Reducers with Immer" page: https://redux-toolkit.js.org/usage/immer-reducers

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants