patches.md
This file
Path
docs/patches.md
168 lines · 6.2 KiB · Markdown
Last changed by
Added egghead.io video embedsMichel Weststratebefore adoptiona866760
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–7why, one step back1---2id: patches3title: Patches4---56<div id="codefund"><!-- fallback content --></div>7Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 8–25why, one step back8<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;">12 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches/embed" ></iframe>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;">21 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients/embed" ></iframe>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>25Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 26–107why, one step back26During 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.2728Patches are useful in few scenarios:2930- To exchange incremental updates with other parties, for example over websockets31- For debugging / traces, to see precisely how state is changed over time32- As basis for undo/redo or as an approach to replay changes on a slightly different state tree3334To 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:3536```javascript37import produce, {applyPatches} from "immer"3839let state = {40 name: "Micheal",41 age: 3242}4344// Let's assume the user is in a wizard, and we don't know whether45// his changes should end up in the base state ultimately or not...46let fork = state47// all the changes the user made in the wizard48let changes = []49// the inverse of all the changes made in the wizard50let inverseChanges = []5152fork = produce(53 fork,54 draft => {55 draft.age = 3356 },57 // The third argument to produce is a callback to which the patches will be fed58 (patches, inversePatches) => {59 changes.push(...patches)60 inverseChanges.push(...inversePatches)61 }62)6364// In the meantime, our original state is replaced, as, for example,65// some changes were received from the server66state = produce(state, draft => {67 draft.name = "Michel"68})6970// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!71state = applyPatches(state, changes)7273// state now contains the changes from both code paths!74expect(state).toEqual({75 name: "Michel", // changed by the server76 age: 33 // changed by the wizard77})7879// Finally, even after finishing the wizard, the user might change his mind and undo his changes...80state = applyPatches(state, inverseChanges)81expect(state).toEqual({82 name: "Michel", // Not reverted83 age: 32 // Reverted84})85```8687The 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:8889```json90[91 {92 "op": "replace",93 "path": ["profile"],94 "value": {"name": "Veria", "age": 5}95 },96 {"op": "remove", "path": ["tags", 3]}97]98```99100```json101[102 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},103 {"op": "add", "path": ["tags", 3], "value": "kiddo"}104]105```106107### `produceWithPatches`Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 108–125why, one step back108109<details>110 <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>111 <br>112 <div style="padding:5px;">113 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality/embed" ></iframe>114 </div>115 <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>116</details>117118<details>119 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 20: Use patches to build redo functionality</summary>120 <br>121 <div style="padding:5px;">122 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality/embed" ></iframe>123 </div>124 <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>125</details>Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 126–168why, one step back126127Instead 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.128129```javascript130import {produceWithPatches} from "immer"131132const [nextState, patches, inversePatches] = produceWithPatches(133 {134 age: 33135 },136 draft => {137 draft.age++138 }139)140```141142Which produces:143144```javascript145;[146 {147 age: 34148 },149 [150 {151 op: "replace",152 path: ["age"],153 value: 34154 }155 ],156 [157 {158 op: "replace",159 path: ["age"],160 value: 33161 }162 ]163]164```165166For 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)167168Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.