Skip to content
Myr

async.mdx

This file

Path

website/docs/async.mdx

59 lines · 2.0 KiB

Last changed by

chore: Merge branch 'unional-prettier'Michel Weststratebefore adoption37eaf8f

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>14<details>15	<summary className="egghead-summary">16		egghead.io lesson 11: Creating <b>async</b> producers (and why you17		shouldn’t)18	</summary>19	<br />20	<div>21		<iframe22			width="760"23			height="427"24			scrolling="no"25			src="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t/embed"26		></iframe>27	</div>28	<a29		className="egghead-link"30		href="https://egghead.io/lessons/react-write-asynchronous-producers-in-immer-and-why-you-shouldn-t"31	>32		Hosted on egghead.io33	</a>34</details>3536## `createDraft` and `finishDraft`3738`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.3940Beyond that, `createDraft` / `finishDraft` could be used to express async updates to drafts:4142```javascript43import {createDraft, finishDraft} from "immer"4445const user = {46	name: "michel",47	todos: []48}4950const draft = createDraft(user)51draft.todos = await (await window.fetch("http://host/" + draft.name)).json()52const loadedUser = finishDraft(draft)53```5455Note: 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.5657Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.5859_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._