Skip to content
Myr

patches.md

This file

Path

docs/patches.md

176 lines · 6.6 KiB · Markdown

Last changed by

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–5why, one step back
1---
2id: patches3title: Patches4---5

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

lines 6–8why, one step back
6<center>
7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

line 9why, one step back
9

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 10–13why, one step back
10<details>
11 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 14: Capture patches using _produceWithPatches_</summary>12 <br>13 <div style="padding:5px;">

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

line 14why, one step back
14 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches/embed" ></iframe>

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 15–22why, one step back
15 </div>
16 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches">Hosted on egghead.io</a>17</details>1819<details>20 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 16: Apply Patches using _applyPatches_</summary>21 <br>22 <div style="padding:5px;">

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

line 23why, one step back
23 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients/embed" ></iframe>

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 24–27why, one step back
24 </div>
25 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients">Hosted on egghead.io</a>26</details>27

Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8

lines 28–29why, one step back
28_⚠ Since version 6 support for Patches has to be enabled explicitly by calling [`enablePatches()`](installation#pick-your-immer-version) once when starting your application._
29

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 30–42why, one step back
30During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer. This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.
3132Patches are useful in few scenarios:3334- To exchange incremental updates with other parties, for example over websockets35- For debugging / traces, to see precisely how state is changed over time36- As basis for undo/redo or as an approach to replay changes on a slightly different state tree3738To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used to record the incremental updates and (inverse) apply them:3940```javascript41import produce, {applyPatches} from "immer"42

chore(docs): mention enablePatchesMichel Weststratebefore adoptionca23093

lines 43–46why, one step back
43// version 6
44import {enablePatches} from "immer"45enablePatches()46

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 47–115why, one step back
47let state = {
48 name: "Micheal",49 age: 3250}5152// Let's assume the user is in a wizard, and we don't know whether53// his changes should end up in the base state ultimately or not...54let fork = state55// all the changes the user made in the wizard56let changes = []57// the inverse of all the changes made in the wizard58let inverseChanges = []5960fork = produce(61 fork,62 draft => {63 draft.age = 3364 },65 // The third argument to produce is a callback to which the patches will be fed66 (patches, inversePatches) => {67 changes.push(...patches)68 inverseChanges.push(...inversePatches)69 }70)7172// In the meantime, our original state is replaced, as, for example,73// some changes were received from the server74state = produce(state, draft => {75 draft.name = "Michel"76})7778// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!79state = applyPatches(state, changes)8081// state now contains the changes from both code paths!82expect(state).toEqual({83 name: "Michel", // changed by the server84 age: 33 // changed by the wizard85})8687// Finally, even after finishing the wizard, the user might change his mind and undo his changes...88state = applyPatches(state, inverseChanges)89expect(state).toEqual({90 name: "Michel", // Not reverted91 age: 32 // Reverted92})93```9495The generated patches are similar (but not the same) to the [RFC-6902 JSON patch standard](http://tools.ietf.org/html/rfc6902), except that the `path` property is an array, rather than a string. This makes processing patches easier. If you want to normalize to the official specification, `patch.path = patch.path.join("/")` should do the trick. Anyway, this is what a bunch of patches and their inverse could look like:9697```json98[99 {100 "op": "replace",101 "path": ["profile"],102 "value": {"name": "Veria", "age": 5}103 },104 {"op": "remove", "path": ["tags", 3]}105]106```107108```json109[110 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},111 {"op": "add", "path": ["tags", 3], "value": "kiddo"}112]113```114115### `produceWithPatches`

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 116–120why, one step back
116
117<details>118 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 19: Using inverse patches to build undo functionality</summary>119 <br>120 <div style="padding:5px;">

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

line 121why, one step back
121 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality/embed" ></iframe>

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 122–129why, one step back
122 </div>
123 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality">Hosted on egghead.io</a>124</details>125126<details>127 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 20: Use patches to build redo functionality</summary>128 <br>129 <div style="padding:5px;">

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

line 130why, one step back
130 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality/embed" ></iframe>

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 131–133why, one step back
131 </div>
132 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality">Hosted on egghead.io</a>133</details>

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 134–176why, one step back
134
135Instead of setting up a patch listener, an easier way to obtain the patches is to use `produceWithPatches`, which has the same signature as `produce`, except that it doesn't return just the next state, but a tuple consisting of `[nextState, patches, inversePatches]`. Like `produce`, `produceWithPatches` supports currying as well.136137```javascript138import {produceWithPatches} from "immer"139140const [nextState, patches, inversePatches] = produceWithPatches(141 {142 age: 33143 },144 draft => {145 draft.age++146 }147)148```149150Which produces:151152```javascript153;[154 {155 age: 34156 },157 [158 {159 op: "replace",160 path: ["age"],161 value: 34162 }163 ],164 [165 {166 op: "replace",167 path: ["age"],168 value: 33169 }170 ]171]172```173174For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)175176Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.