patches.mdx
This file
Path
website/docs/patches.mdx
224 lines · 6.7 KiB
Last changed by
docs: fix typo in patches.mdx (#1086)Andrej Lamovbefore adoptioncb47d50
History of this fileTake it
The walk stopped after 200 commits: lines older than 6555173 point at it.
fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 1–11why, one step back1---2id: patches3title: Patches4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 12why, one step back12</center> <details>fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 13–30why, one step back13 <summary className="egghead-summary">14 egghead.io lesson 14: Capture patches using _produceWithPatches_15 </summary>16 <br />17 <div>18 <iframe19 width="760"20 height="427"21 scrolling="no"22 src="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches/embed"23 ></iframe>24 </div>25 <a26 className="egghead-link"27 href="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches"28 >29 Hosted on egghead.io30 </a>Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 31why, one step back31</details> <details>fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 32–64why, one step back32 <summary className="egghead-summary">33 egghead.io lesson 16: Apply Patches using _applyPatches_34 </summary>35 <br />36 <div>37 <iframe38 width="760"39 height="427"40 scrolling="no"41 src="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients/embed"42 ></iframe>43 </div>44 <a45 className="egghead-link"46 href="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients"47 >48 Hosted on egghead.io49 </a>50</details>5152_⚠ Since version 6 support for Patches has to be enabled explicitly by calling [`enablePatches()`](./installation.mdx#pick-your-immer-version) once when starting your application._5354During 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.5556Patches are useful in few scenarios:5758- To exchange incremental updates with other parties, for example over websockets59- For debugging / traces, to see precisely how state is changed over time60- As basis for undo/redo or as an approach to replay changes on a slightly different state tree6162To 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:6364```javascriptMerge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 65why, one step back65import {produce, applyPatches} from "immer"fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 66–118why, one step back6667// version 668import {enablePatches} from "immer"69enablePatches()7071let state = {72 name: "Micheal",73 age: 3274}7576// Let's assume the user is in a wizard, and we don't know whether77// his changes should end up in the base state ultimately or not...78let fork = state79// all the changes the user made in the wizard80let changes = []81// the inverse of all the changes made in the wizard82let inverseChanges = []8384fork = produce(85 fork,86 draft => {87 draft.age = 3388 },89 // The third argument to produce is a callback to which the patches will be fed90 (patches, inversePatches) => {91 changes.push(...patches)92 inverseChanges.push(...inversePatches)93 }94)9596// In the meantime, our original state is replaced, as, for example,97// some changes were received from the server98state = produce(state, draft => {99 draft.name = "Michel"100})101102// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!103state = applyPatches(state, changes)104105// state now contains the changes from both code paths!106expect(state).toEqual({107 name: "Michel", // changed by the server108 age: 33 // changed by the wizard109})110111// Finally, even after finishing the wizard, the user might change his mind and undo his changes...112state = applyPatches(state, inverseChanges)113expect(state).toEqual({114 name: "Michel", // Not reverted115 age: 32 // Reverted116})117```118docs: fixing link to RFC-6902 & fixing typo (#830)Connor Burtonbefore adoption648d39b
line 119why, one step back119The generated patches are similar (but not the same) to the [RFC-6902 JSON patch standard](https://datatracker.ietf.org/doc/html/rfc6902/#section-4.1), 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:fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 120–138why, one step back120121```json122[123 {124 "op": "replace",125 "path": ["profile"],126 "value": {"name": "Veria", "age": 5}127 },128 {"op": "remove", "path": ["tags", 3]}129]130```131132```json133[134 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},135 {"op": "add", "path": ["tags", 3], "value": "kiddo"}136]137```138docs: fixing link to RFC-6902 & fixing typo (#830)Connor Burtonbefore adoption648d39b
line 139why, one step back139⚠ 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 potentially computationally very expensive. So in cases you might want to post process the generated patches, or compress them as explained below.fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 140–161why, one step back140141### `produceWithPatches`142143<details>144 <summary className="egghead-summary">145 egghead.io lesson 19: Using inverse patches to build undo functionality146 </summary>147 <br />148 <div>149 <iframe150 width="760"151 height="427"152 scrolling="no"153 src="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality/embed"154 ></iframe>155 </div>156 <a157 className="egghead-link"158 href="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality"159 >160 Hosted on egghead.io161 </a>Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42
line 162why, one step back162</details> <details>fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 163–200why, one step back163 <summary className="egghead-summary">164 egghead.io lesson 20: Use patches to build redo functionality165 </summary>166 <br />167 <div>168 <iframe169 width="760"170 height="427"171 scrolling="no"172 src="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality/embed"173 ></iframe>174 </div>175 <a176 className="egghead-link"177 href="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality"178 >179 Hosted on egghead.io180 </a>181</details>182183Instead 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.184185```javascript186import {produceWithPatches} from "immer"187188const [nextState, patches, inversePatches] = produceWithPatches(189 {190 age: 33191 },192 draft => {193 draft.age++194 }195)196```197198Which produces:199200```javascriptdocs: fix typo in patches.mdx (#1086)Andrej Lamovbefore adoptioncb47d50
line 201why, one step back201[fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173
lines 202–224why, one step back202 {203 age: 34204 },205 [206 {207 op: "replace",208 path: ["age"],209 value: 34210 }211 ],212 [213 {214 op: "replace",215 path: ["age"],216 value: 33217 }218 ]219]220```221222For 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)223224Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.