update-patterns.md
This file
Path
website/docs/update-patterns.md
166 lines · 4.3 KiB · Markdown
Last changed by
docs: added update-pattern on how to replace & bulk update (nested) objects (#1131)Matt van Voorstbefore adoption7050550
History of this fileTake it
docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 1–6why, one step back1---2id: update-patterns3title: Update patterns4---56<center>chore: docusaurus upgradeMichel Weststratebefore adoption48a91b3
line 7why, one step back7<div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div>docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 8–16why, one step back8</center>910Working 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```javascriptMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 17why, one step back17import {produce} from "immer"docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 18–28why, one step back1819const 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})28docs: Update update-patterns.md to resetting/clearing (#1082)siddtheonebefore adoption17ac0b8
line 29why, one step back29// delete single propertydocs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 30–37why, one step back30const deletedTodosObj = produce(todosObj, draft => {31 delete draft["id1"]32})3334// update35const updatedTodosObj = produce(todosObj, draft => {36 draft["id1"].done = true37})docs: Update update-patterns.md to resetting/clearing (#1082)siddtheonebefore adoption17ac0b8
line 38why, one step back38docs: added update-pattern on how to replace & bulk update (nested) objects (#1131)Matt van Voorstbefore adoption7050550
lines 39–46why, one step back39// replace & update in bulk40const updatedTodosObj = produce(todosObj, draft => {41 Object.assign(draft, {42 id1: {done: true, body: "Take out the trash"},43 id2: {done: true, body: "Check Email"},44 id3: {done: true, body: "Feed my cat"}45 })46docs: Update update-patterns.md to resetting/clearing (#1082)siddtheonebefore adoption17ac0b8
lines 47–50why, one step back47// reset/clear/empty48const emptyTodo = produce(todosObj, () => {49 return {};50})docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
line 51why, one step back51```docs: added update-pattern on how to replace & bulk update (nested) objects (#1131)Matt van Voorstbefore adoption7050550
lines 52–53why, one step back5253Any time a nested draft field gets a new reference or value, produce() will finish applying the immutable update and return a new reference. If you tried to mutate, but the values remained the same, Immer will bail out and return the existing reference from produce()docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 54–57why, one step back5455### Array mutations5657```javascriptMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 58why, one step back58import {produce} from "immer"docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 59–118why, one step back5960const todosArray = [61 {id: "id1", done: false, body: "Take out the trash"},62 {id: "id2", done: false, body: "Check Email"}63]6465// add66const addedTodosArray = produce(todosArray, draft => {67 draft.push({id: "id3", done: false, body: "Buy bananas"})68})6970// delete by index71const deletedTodosArray = produce(todosArray, draft => {72 draft.splice(3 /*the index */, 1)73})7475// update by index76const updatedTodosArray = produce(todosArray, draft => {77 draft[3].done = true78})7980// insert at index81const updatedTodosArray = produce(todosArray, draft => {82 draft.splice(3, 0, {id: "id3", done: false, body: "Buy bananas"})83})8485// remove last item86const updatedTodosArray = produce(todosArray, draft => {87 draft.pop()88})8990// remove first item91const updatedTodosArray = produce(todosArray, draft => {92 draft.shift()93})9495// add item at the beginning of the array96const addedTodosArray = produce(todosArray, draft => {97 draft.unshift({id: "id3", done: false, body: "Buy bananas"})98})99100// delete by id101const deletedTodosArray = produce(todosArray, draft => {102 const index = draft.findIndex(todo => todo.id === "id1")103 if (index !== -1) draft.splice(index, 1)104})105106// update by id107const updatedTodosArray = produce(todosArray, draft => {108 const index = draft.findIndex(todo => todo.id === "id1")109 if (index !== -1) draft[index].done = true110})111112// filtering items113const updatedTodosArray = produce(todosArray, draft => {114 // creating a new state is simpler in this example115 // (note that we don't need produce in this case,116 // but as shown below, if the filter is not on the top117 // level produce is still pretty useful)118 return draft.filter(todo => todo.done)docs: Update update-patterns.md to resetting/clearing (#1082)siddtheonebefore adoption17ac0b8
lines 119–123why, one step back119})120121// reset/clear/empty122const emptyTodo = produce(todosArray, () => {123 return [];docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 124–129why, one step back124})125```126127### Nested data structures128129```javascriptMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 130why, one step back130import {produce} from "immer"docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 131–158why, one step back131132// example complex data structure133const store = {134 users: new Map([135 [136 "17",137 {138 name: "Michel",139 todos: [140 {141 title: "Get coffee",142 done: false143 }144 ]145 }146 ]147 ])148}149150// updating something deeply in-an-object-in-an-array-in-a-map-in-an-object:151const nextStore = produce(store, draft => {152 draft.users.get("17").todos[0].done = true153})154155// filtering out all unfinished todo's156const nextStore = produce(store, draft => {157 const user = draft.users.get("17")158 // when filtering, creating a fresh collection is simpler thanchore: typo irrelvant => irrelevant (#866)Yanick Champouxbefore adoptionb6bf265
line 159why, one step back159 // removing irrelevant itemsdocs: unfinished todo filter condition (#1155)Ishrath Inaambefore adoption857b4b7
line 160why, one step back160 user.todos = user.todos.filter(todo => !todo.done)docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 161–166why, one step back161})162```163164Note 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)`.165166Note 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.