Skip to content

Include common add, delete, and update patterns in README? #115

Description

@christiangenco

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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions