-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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
[Refactor] Update all React Toolkit slices to use mutating syntax #358
Comments
Note that additional "mutation" could be done here. For example, in toggleFavoriteNotes: (state, { payload }: PayloadAction<string>) => {
state.notes = state.selectedNotesIds.includes(payload)
? state.notes.map((note) =>
state.selectedNotesIds.includes(note.id) ? { ...note, favorite: !note.favorite } : note
)
: state.notes.map((note) =>
note.id === payload ? { ...note, favorite: !note.favorite } : note
)
}, That could potentially be rewritten along these lines: toggleFavoriteNotes: (state, { payload }: PayloadAction<string>) => {
const toggleSelected = state.selectedNotesIds.includes(payload);
// Can use a `forEach` loop instead of a `map()` - no need to create a new array manually
state.notes.forEach(note => {
const shouldToggle = toggleSelected ? state.selectedNotesIds.includes(note.id) : note.id === payload
if (shouldToggle) {
// Can directly "mutate" a given note entry
note.favorite = !note.favorite
}
})
}, |
@markerikson Thanks for the tip! I went through and only updated the "top level" mutations, but I definitely left a lot of |
Yeah. One of the great things about Immer is that you can grab out nested values, "mutate" those nested values seemingly by themselves, and Immer does all the work of tracking the parents that need to get copied too. Like, in this case, |
Use:
Instead of:
The text was updated successfully, but these errors were encountered: