update-patterns.md
This file
Path
website/docs/update-patterns.md
166 lines · 4.3 KiB · Markdown
Last changed by
chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167---id: update-patternstitle: Update patterns---
<center><div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div></center>
Working with immutable data, before Immer, used to mean learning all the immutable update patterns.
To help 'unlearning' those patterns here is an overview how you can leverage the built-in JavaScript APIs to update objects and collections:
### Object mutations
```javascriptimport {produce} from "immer"
const todosObj = { id1: {done: false, body: "Take out the trash"}, id2: {done: false, body: "Check Email"}}
// addconst addedTodosObj = produce(todosObj, draft => { draft["id3"] = {done: false, body: "Buy bananas"}})
// delete single propertyconst deletedTodosObj = produce(todosObj, draft => { delete draft["id1"]})
// updateconst updatedTodosObj = produce(todosObj, draft => { draft["id1"].done = true})
// replace & update in bulkconst updatedTodosObj = produce(todosObj, draft => { Object.assign(draft, { id1: {done: true, body: "Take out the trash"}, id2: {done: true, body: "Check Email"}, id3: {done: true, body: "Feed my cat"} })
// reset/clear/emptyconst emptyTodo = produce(todosObj, () => { return {};})```
Any 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()
### Array mutations
```javascriptimport {produce} from "immer"
const todosArray = [ {id: "id1", done: false, body: "Take out the trash"}, {id: "id2", done: false, body: "Check Email"}]
// addconst addedTodosArray = produce(todosArray, draft => { draft.push({id: "id3", done: false, body: "Buy bananas"})})
// delete by indexconst deletedTodosArray = produce(todosArray, draft => { draft.splice(3 /*the index */, 1)})
// update by indexconst updatedTodosArray = produce(todosArray, draft => { draft[3].done = true})
// insert at indexconst updatedTodosArray = produce(todosArray, draft => { draft.splice(3, 0, {id: "id3", done: false, body: "Buy bananas"})})
// remove last itemconst updatedTodosArray = produce(todosArray, draft => { draft.pop()})
// remove first itemconst updatedTodosArray = produce(todosArray, draft => { draft.shift()})
// add item at the beginning of the arrayconst addedTodosArray = produce(todosArray, draft => { draft.unshift({id: "id3", done: false, body: "Buy bananas"})})
// delete by idconst deletedTodosArray = produce(todosArray, draft => { const index = draft.findIndex(todo => todo.id === "id1") if (index !== -1) draft.splice(index, 1)})
// update by idconst updatedTodosArray = produce(todosArray, draft => { const index = draft.findIndex(todo => todo.id === "id1") if (index !== -1) draft[index].done = true})
// filtering itemsconst updatedTodosArray = produce(todosArray, draft => { // creating a new state is simpler in this example // (note that we don't need produce in this case, // but as shown below, if the filter is not on the top // level produce is still pretty useful) return draft.filter(todo => todo.done)})
// reset/clear/emptyconst emptyTodo = produce(todosArray, () => { return []})```
### Nested data structures
```javascriptimport {produce} from "immer"
// example complex data structureconst store = { users: new Map([ [ "17", { name: "Michel", todos: [ { title: "Get coffee", done: false } ] } ] ])}
// updating something deeply in-an-object-in-an-array-in-a-map-in-an-object:const nextStore = produce(store, draft => { draft.users.get("17").todos[0].done = true})
// filtering out all unfinished todo'sconst nextStore = produce(store, draft => { const user = draft.users.get("17") // when filtering, creating a fresh collection is simpler than // removing irrelevant items user.todos = user.todos.filter(todo => !todo.done)})```
Note 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)`.
Note 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.