Skip to content
Myr

async.mdx

This file

Path

website/docs/async.mdx

58 lines · 2.0 KiB

Last changed by

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

History of this file

Take it

1---2id: async3title: createDraft / finishDraft4sidebar_label: createDraft / finishDraft5---67<center>8	<div9		data-ea-publisher="immerjs"10		data-ea-type="image"11		className="horizontal bordered"12	></div>13</center> <details>14	<summary className="egghead-summary">15		egghead.io lesson 11: Creating <b>async</b> producers (and why you16		shouldn’t)17	</summary>18	<br />19	<div>20		<iframe21			width="760"22			height="427"23			scrolling="no"24			src="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t/embed"25		></iframe>26	</div>27	<a28		className="egghead-link"29		href="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t"30	>31		Hosted on egghead.io32	</a>33</details>3435## `createDraft` and `finishDraft`3637`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced.3839Beyond that, `createDraft` / `finishDraft` could be used to express async updates to drafts:4041```javascript42import {createDraft, finishDraft} from "immer"4344const user = {45	name: "michel",46	todos: []47}4849const draft = createDraft(user)50draft.todos = await (await window.fetch("http://host/" + draft.name)).json()51const loadedUser = finishDraft(draft)52```5354Note: The above is an anti-pattern! First fetch data instead, then draft the `user`. Otherwise updates to user that happen during the async process, would be "missed" by the draft.5556Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.5758_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._