update-patterns.md
This file
Path
docs/update-patterns.md
146 lines · 3.6 KiB · Markdown
Last changed by
docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
History of this fileTake it
Immer 7Michel Weststratebefore adoption467ea5d
lines 1–5why, one step back1---2id: update-patterns3title: Update patterns4---5docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 6–8why, one step back6<center>7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>Immer 7Michel Weststratebefore adoption467ea5d
lines 9–146why, one step back910Working with immutable data, before Immer, used to mean learning all the immutable update patterns.1112To help 'unlearning' those patterns here is an overview how you can leverage the built-in JavaScript APIs to update objects and collections:1314### Object mutations1516```javascript17import produce from "immer"1819const todosObj = {20 id1: {done: false, body: "Take out the trash"},21 id2: {done: false, body: "Check Email"}22}2324// add25const addedTodosObj = produce(todosObj, draft => {26 draft["id3"] = {done: false, body: "Buy bananas"}27})2829// delete30const deletedTodosObj = produce(todosObj, draft => {31 delete draft["id1"]32})3334// update35const updatedTodosObj = produce(todosObj, draft => {36 draft["id1"].done = true37})38```3940### Array mutations4142```javascript43import produce from "immer"4445const todosArray = [46 {id: "id1", done: false, body: "Take out the trash"},47 {id: "id2", done: false, body: "Check Email"}48]4950// add51const addedTodosArray = produce(todosArray, draft => {52 draft.push({id: "id3", done: false, body: "Buy bananas"})53})5455// delete by index56const deletedTodosArray = produce(todosArray, draft => {57 draft.splice(3 /*the index */, 1)58})5960// update by index61const updatedTodosArray = produce(todosArray, draft => {62 draft[3].done = true63})6465// insert at index66const updatedTodosArray = produce(todosArray, draft => {67 draft.splice(3, 0, {id: "id3", done: false, body: "Buy bananas"})68})6970// remove last item71const updatedTodosArray = produce(todosArray, draft => {72 draft.pop()73})7475// remove first item76const updatedTodosArray = produce(todosArray, draft => {77 draft.shift()78})7980// add item at the beginning of the array81const addedTodosArray = produce(todosArray, draft => {82 draft.unshift({id: "id3", done: false, body: "Buy bananas"})83})8485// delete by id86const deletedTodosArray = produce(todosArray, draft => {87 const index = draft.findIndex(todo => todo.id === "id1")88 if (index !== -1) draft.splice(index, 1)89})9091// update by id92const updatedTodosArray = produce(todosArray, draft => {93 const index = draft.findIndex(todo => todo.id === "id1")94 if (index !== -1) draft[index].done = true95})9697// filtering items98const updatedTodosArray = produce(todosArray, draft => {99 // creating a new state is simpler in this example100 // (note that we don't need produce in this case,101 // but as shown below, if the filter is not on the top102 // level produce is still pretty useful)103 return draft.filter(todo => todo.done)104})105```106107### Nested data structures108109```javascript110import produce from "immer"111112// example complex data structure113const store = {114 users: new Map([115 [116 "17",117 {118 name: "Michel",119 todos: [120 {121 title: "Get coffee",122 done: false123 }124 ]125 }126 ]127 ])128}129130// updating something deeply in-an-object-in-an-array-in-a-map-in-an-object:131const nextStore = produce(store, draft => {132 draft.users.get("17").todos[0].done = true133})134135// filtering out all unfinished todo's136const nextStore = produce(store, draft => {137 const user = draft.users.get("17")138 // when filtering, creating a fresh collection is simpler than139 // removing irrelvant items140 user.todos = user.todos.filter(todo => todo.done)141})142```143144Note that many array operations can be used to insert multiple items at once by passing multiple arguments or using the spread operation: `todos.unshift(...items)`.145146Note that when working with arrays that contain objects that are typically identified by some id, we recommend to use `Map` or index based objects (as shown above) instead of performing frequent find operations, lookup tables perform much better in general.