Skip to content
Myr

patches.md

This file

Path

docs/patches.md

170 lines · 6.4 KiB · Markdown

Last changed by

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

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–109why, 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"4041let state = {42 name: "Micheal",43 age: 3244}4546// Let's assume the user is in a wizard, and we don't know whether47// his changes should end up in the base state ultimately or not...48let fork = state49// all the changes the user made in the wizard50let changes = []51// the inverse of all the changes made in the wizard52let inverseChanges = []5354fork = produce(55 fork,56 draft => {57 draft.age = 3358 },59 // The third argument to produce is a callback to which the patches will be fed60 (patches, inversePatches) => {61 changes.push(...patches)62 inverseChanges.push(...inversePatches)63 }64)6566// In the meantime, our original state is replaced, as, for example,67// some changes were received from the server68state = produce(state, draft => {69 draft.name = "Michel"70})7172// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!73state = applyPatches(state, changes)7475// state now contains the changes from both code paths!76expect(state).toEqual({77 name: "Michel", // changed by the server78 age: 33 // changed by the wizard79})8081// Finally, even after finishing the wizard, the user might change his mind and undo his changes...82state = applyPatches(state, inverseChanges)83expect(state).toEqual({84 name: "Michel", // Not reverted85 age: 32 // Reverted86})87```8889The 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:9091```json92[93 {94 "op": "replace",95 "path": ["profile"],96 "value": {"name": "Veria", "age": 5}97 },98 {"op": "remove", "path": ["tags", 3]}99]100```101102```json103[104 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},105 {"op": "add", "path": ["tags", 3], "value": "kiddo"}106]107```108109### `produceWithPatches`

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 110–114why, one step back
110
111<details>112 <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>113 <br>114 <div style="padding:5px;">

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

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

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

line 124why, one step back
124 <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 125–127why, one step back
125 </div>
126 <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>127</details>

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 128–170why, one step back
128
129Instead 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.130131```javascript132import {produceWithPatches} from "immer"133134const [nextState, patches, inversePatches] = produceWithPatches(135 {136 age: 33137 },138 draft => {139 draft.age++140 }141)142```143144Which produces:145146```javascript147;[148 {149 age: 34150 },151 [152 {153 op: "replace",154 path: ["age"],155 value: 34156 }157 ],158 [159 {160 op: "replace",161 path: ["age"],162 value: 33163 }164 ]165]166```167168For 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)169170Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.