I've spent so long thinking about immutable ways to update objects and arrays that I had trouble wrapping my head around using mutating methods again, as is needed with immer.
It would've helped me get started faster if simple "best practice" examples similar to these were included in the docs:
import produce from "immer";
// object mutations
const todosObj = {
id1: { done: false, body: "Take out the trash" },
id2: { done: false, body: "Check Email" }
};
// add
const addedTodosObj = produce(todosObj, draft => {
draft["id3"] = { done: false, body: "Buy bananas" };
});
// delete
const deletedTodosObj = produce(todosObj, draft => {
delete draft["id1"];
});
// update
const updatedTodosObj = produce(todosObj, draft => {
draft["id1"].done = true;
});
// array mutations
const todosArray = [
{ id: "id1", done: false, body: "Take out the trash" },
{ id: "id2", done: false, body: "Check Email" }
];
// add
const addedTodosArray = produce(todosArray, draft => {
draft.push({ id: "id3", done: false, body: "Buy bananas" });
});
// delete
const deletedTodosArray = produce(todosArray, draft => {
draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);
});
// update
const updatedTodosArray = produce(todosArray, draft => {
draft[draft.findIndex(todo => todo.id === "id1")].done = true;
});
...though I'm not positive draft.splice(draft.findIndex(todo => todo.id === "id1"), 1) is the best way to delete an item from an array mutably. This is a case where the immutable draft.filter(todo => todo.id !== "id1") seems less verbose.
I've spent so long thinking about immutable ways to update objects and arrays that I had trouble wrapping my head around using mutating methods again, as is needed with
immer.It would've helped me get started faster if simple "best practice" examples similar to these were included in the docs:
...though I'm not positive
draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)is the best way to delete an item from an array mutably. This is a case where the immutabledraft.filter(todo => todo.id !== "id1")seems less verbose.