patches.md
This file
Path
docs/patches.md
178 lines · 7.1 KiB · Markdown
Last changed by
docs: clarify that patches are not optimal. Solves #648Michel Weststratebefore adoption41673f4
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–5why, one step back1---2id: patches3title: Patches4---5docs: updated sponsor linksMichel Weststratebefore adoptionf97d037
lines 6–8why, one step back6<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 back9Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 10–13why, one step back10<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 back14 <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 back15 </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 back23 <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 back24 </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>27Merge pull request #536 from immerjs/multi-bundleMichel Weststratebefore adoption0d87fc8
lines 28–29why, one step back28_⚠ Since version 6 support for Patches has to be enabled explicitly by calling [`enablePatches()`](installation#pick-your-immer-version) once when starting your application._29Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 30–42why, one step back30During 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"42chore(docs): mention enablePatchesMichel Weststratebefore adoptionca23093
lines 43–46why, one step back43// version 644import {enablePatches} from "immer"45enablePatches()46Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 47–114why, one step back47let 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```114docs: clarify that patches are not optimal. Solves #648Michel Weststratebefore adoption41673f4
lines 115–116why, one step back115⚠ Note: The set of patches generated by Immer should be correct, that is, applying them to an equal base object should result in the same end state. However Immer does not guarantee the generated set of patches will be optimal, that is, the minimum set of patches possible. It depends often on the use case what is considered 'optimal', and generating the optimal set of patches is potentielly computationally very expensive. So in cases you might want to post process the generated patches, or compress them as explained below.116Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
line 117why, one step back117### `produceWithPatches`Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 118–122why, one step back118119<details>120 <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>121 <br>122 <div style="padding:5px;">docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585
line 123why, one step back123 <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 124–131why, one step back124 </div>125 <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>126</details>127128<details>129 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 20: Use patches to build redo functionality</summary>130 <br>131 <div style="padding:5px;">docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585
line 132why, one step back132 <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 133–135why, one step back133 </div>134 <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>135</details>Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 136–178why, one step back136137Instead 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.138139```javascript140import {produceWithPatches} from "immer"141142const [nextState, patches, inversePatches] = produceWithPatches(143 {144 age: 33145 },146 draft => {147 draft.age++148 }149)150```151152Which produces:153154```javascript155;[156 {157 age: 34158 },159 [160 {161 op: "replace",162 path: ["age"],163 value: 34164 }165 ],166 [167 {168 op: "replace",169 path: ["age"],170 value: 33171 }172 ]173]174```175176For 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)177178Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.