Skip to content
Myr

patches.md

This file

Path

docs/patches.md

174 lines · 6.5 KiB · Markdown

Last changed by

chore(docs): mention enablePatchesMichel Weststratebefore adoptionca23093

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–7why, one step back
1---
2id: patches3title: Patches4---56<div id="codefund"><!-- fallback content --></div>7

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

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

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

line 12why, one step back
12 <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 13–20why, one step back
13 </div>
14 <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>15</details>1617<details>18 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 16: Apply Patches using _applyPatches_</summary>19 <br>20 <div style="padding:5px;">

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

line 21why, one step back
21 <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 22–25why, one step back
22 </div>
23 <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>24</details>25

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

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

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 28–40why, one step back
28During 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.
2930Patches are useful in few scenarios:3132- To exchange incremental updates with other parties, for example over websockets33- For debugging / traces, to see precisely how state is changed over time34- As basis for undo/redo or as an approach to replay changes on a slightly different state tree3536To 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:3738```javascript39import produce, {applyPatches} from "immer"40

chore(docs): mention enablePatchesMichel Weststratebefore adoptionca23093

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

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 45–113why, one step back
45let state = {
46 name: "Micheal",47 age: 3248}4950// Let's assume the user is in a wizard, and we don't know whether51// his changes should end up in the base state ultimately or not...52let fork = state53// all the changes the user made in the wizard54let changes = []55// the inverse of all the changes made in the wizard56let inverseChanges = []5758fork = produce(59 fork,60 draft => {61 draft.age = 3362 },63 // The third argument to produce is a callback to which the patches will be fed64 (patches, inversePatches) => {65 changes.push(...patches)66 inverseChanges.push(...inversePatches)67 }68)6970// In the meantime, our original state is replaced, as, for example,71// some changes were received from the server72state = produce(state, draft => {73 draft.name = "Michel"74})7576// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!77state = applyPatches(state, changes)7879// state now contains the changes from both code paths!80expect(state).toEqual({81 name: "Michel", // changed by the server82 age: 33 // changed by the wizard83})8485// Finally, even after finishing the wizard, the user might change his mind and undo his changes...86state = applyPatches(state, inverseChanges)87expect(state).toEqual({88 name: "Michel", // Not reverted89 age: 32 // Reverted90})91```9293The 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:9495```json96[97 {98 "op": "replace",99 "path": ["profile"],100 "value": {"name": "Veria", "age": 5}101 },102 {"op": "remove", "path": ["tags", 3]}103]104```105106```json107[108 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},109 {"op": "add", "path": ["tags", 3], "value": "kiddo"}110]111```112113### `produceWithPatches`

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 114–118why, one step back
114
115<details>116 <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>117 <br>118 <div style="padding:5px;">

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

line 119why, one step back
119 <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 120–127why, one step back
120 </div>
121 <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>122</details>123124<details>125 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 20: Use patches to build redo functionality</summary>126 <br>127 <div style="padding:5px;">

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

line 128why, one step back
128 <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 129–131why, one step back
129 </div>
130 <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>131</details>

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 132–174why, one step back
132
133Instead 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.134135```javascript136import {produceWithPatches} from "immer"137138const [nextState, patches, inversePatches] = produceWithPatches(139 {140 age: 33141 },142 draft => {143 draft.age++144 }145)146```147148Which produces:149150```javascript151;[152 {153 age: 34154 },155 [156 {157 op: "replace",158 path: ["age"],159 value: 34160 }161 ],162 [163 {164 op: "replace",165 path: ["age"],166 value: 33167 }168 ]169]170```171172For 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)173174Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.