Points to learn about IMMER
- If you return anything other than draft from the recipe function, that return value will replace the state
- You mostly want to mutate the draft to mutate the state, ** so returning draft after modifying it is optional**, the
immer
will return finalized draft anyway
- if you return anything else from
recipe
function then as per point 1, the new return value will replace the state
- Point 3 is ok, only if you do not modify the draft in your recipe function. i.e. you can choose one of the two
a. modify the draft --> return draft or undefined, either is ok
b. want to return some new value, then don't touch the draft at all
Now coming to answer for the question.
this is your reducer function
(state, action) => state.token = action.payload.test
This function is doing two things,
1. modifying state
2. returning action.payload.test
so it's violating point 4 and hence the error from Immer library
in this specific case, intention is only to modify the state, so we have to undo the existing return with void
setToken: (state, action) => void(state.token = action.payload.test)
However, Immer library recommends the use of code block to insure consistency across large code-base, this code block implicitly returns undefined
setToken: (state, action) => { state.token = action.payload.test }