Skip to content
Myr

patches.mdx

This file

Path

website/docs/patches.mdx

227 lines · 6.8 KiB

Last changed by

docs: fix RFC-6902 JSON Pointer path conversion (#1274)Hashim Khanbefore adoptionf5ae31f

History of this file

Take it

1---2id: patches3title: Patches4---56<center>7	<div8		data-ea-publisher="immerjs"9		data-ea-type="image"10		className="horizontal bordered"11	></div>12</center>13<details>14	<summary className="egghead-summary">15		egghead.io lesson 14: Capture patches using _produceWithPatches_16	</summary>17	<br />18	<div>19		<iframe20			width="760"21			height="427"22			scrolling="no"23			src="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches/embed"24		></iframe>25	</div>26	<a27		className="egghead-link"28		href="https://egghead.io/lessons/react-capture-patches-to-distribute-changes-in-app-state-with-immer-producewithpatches"29	>30		Hosted on egghead.io31	</a>32</details>33<details>34	<summary className="egghead-summary">35		egghead.io lesson 16: Apply Patches using _applyPatches_36	</summary>37	<br />38	<div>39		<iframe40			width="760"41			height="427"42			scrolling="no"43			src="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients/embed"44		></iframe>45	</div>46	<a47		className="egghead-link"48		href="https://egghead.io/lessons/react-apply-patches-using-immer-applypatches-to-synchronize-state-across-clients"49	>50		Hosted on egghead.io51	</a>52</details>5354_⚠ 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._5556During 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.5758Patches are useful in few scenarios:5960- To exchange incremental updates with other parties, for example over websockets61- For debugging / traces, to see precisely how state is changed over time62- As basis for undo/redo or as an approach to replay changes on a slightly different state tree6364To 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:6566```javascript67import {produce, applyPatches} from "immer"6869// version 670import {enablePatches} from "immer"71enablePatches()7273let state = {74	name: "Micheal",75	age: 3276}7778// Let's assume the user is in a wizard, and we don't know whether79// his changes should end up in the base state ultimately or not...80let fork = state81// all the changes the user made in the wizard82let changes = []83// the inverse of all the changes made in the wizard84let inverseChanges = []8586fork = produce(87	fork,88	draft => {89		draft.age = 3390	},91	// The third argument to produce is a callback to which the patches will be fed92	(patches, inversePatches) => {93		changes.push(...patches)94		inverseChanges.push(...inversePatches)95	}96)9798// In the meantime, our original state is replaced, as, for example,99// some changes were received from the server100state = produce(state, draft => {101	draft.name = "Michel"102})103104// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!105state = applyPatches(state, changes)106107// state now contains the changes from both code paths!108expect(state).toEqual({109	name: "Michel", // changed by the server110	age: 33 // changed by the wizard111})112113// Finally, even after finishing the wizard, the user might change his mind and undo his changes...114state = applyPatches(state, inverseChanges)115expect(state).toEqual({116	name: "Michel", // Not reverted117	age: 32 // Reverted118})119```120121The 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, use `patch.path = "/" + patch.path.join("/")` so the result is a JSON Pointer with a leading `/` (and escape `~` / `/` in path tokens per [RFC-6901](https://datatracker.ietf.org/doc/html/rfc6901) when needed). Anyway, this is what a bunch of patches and their inverse could look like:122123```json124[125	{126		"op": "replace",127		"path": ["profile"],128		"value": {"name": "Veria", "age": 5}129	},130	{"op": "remove", "path": ["tags", 3]}131]132```133134```json135[136	{"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},137	{"op": "add", "path": ["tags", 3], "value": "kiddo"}138]139```140141⚠ 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.142143### `produceWithPatches`144145<details>146	<summary className="egghead-summary">147		egghead.io lesson 19: Using inverse patches to build undo functionality148	</summary>149	<br />150	<div>151		<iframe152			width="760"153			height="427"154			scrolling="no"155			src="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality/embed"156		></iframe>157	</div>158	<a159		className="egghead-link"160		href="https://egghead.io/lessons/react-use-immer-inversepatches-to-build-undo-functionality"161	>162		Hosted on egghead.io163	</a>164</details>165<details>166	<summary className="egghead-summary">167		egghead.io lesson 20: Use patches to build redo functionality168	</summary>169	<br />170	<div>171		<iframe172			width="760"173			height="427"174			scrolling="no"175			src="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality/embed"176		></iframe>177	</div>178	<a179		className="egghead-link"180		href="https://egghead.io/lessons/react-use-immer-patches-to-build-redo-functionality"181	>182		Hosted on egghead.io183	</a>184</details>185186Instead 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.187188```javascript189import {produceWithPatches} from "immer"190191const [nextState, patches, inversePatches] = produceWithPatches(192	{193		age: 33194	},195	draft => {196		draft.age++197	}198)199```200201Which produces:202203```javascript204;[205	{206		age: 34207	},208	[209		{210			op: "replace",211			path: ["age"],212			value: 34213		}214	],215	[216		{217			op: "replace",218			path: ["age"],219			value: 33220		}221	]222]223```224225For 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)226227Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.