Skip to content
Myr

Added examples as suggested by #115

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Michel Weststrate · committed by Michel Weststrate · parent 8e61145 · Browse files · 1 file+52 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+52 added−0 removed

  • other:+52 added−0 removed

1 file+52 added−0 removed

modified:readme.md+52 added
304 unmodified lines
305## How does Immer work?306307Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).308309## Example patterns.310311_For those who have to go back to thinking in object updates :-)_312313```javscript314import produce from "immer";315316// object mutations317const todosObj = {318 id1: { done: false, body: "Take out the trash" },319 id2: { done: false, body: "Check Email" }320};321322// add323const addedTodosObj = produce(todosObj, draft => {324 draft["id3"] = { done: false, body: "Buy bananas" };325});326327// delete328const deletedTodosObj = produce(todosObj, draft => {329 delete draft["id1"];330});331332// update333const updatedTodosObj = produce(todosObj, draft => {334 draft["id1"].done = true;335});336337// array mutations338const todosArray = [339 { id: "id1", done: false, body: "Take out the trash" },340 { id: "id2", done: false, body: "Check Email" }341];342343// add344const addedTodosArray = produce(todosArray, draft => {345 draft.push({ id: "id3", done: false, body: "Buy bananas" });346});347348// delete349const deletedTodosArray = produce(todosArray, draft => {350 draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);351 // or (slower):352 // return draft.filter(todo => todo.id !== "id1")353});354355// update356const updatedTodosArray = produce(todosArray, draft => {357 draft[draft.findIndex(todo => todo.id === "id1")].done = true;358});359```360361## Performance362363Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer.364This test takes 100.000 todo items, and updates 10.000 of them.
55 unmodified lines