async.mdx
This file
Path
website/docs/async.mdx
71 lines · 2.5 KiB
Last changed by
docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
History of this fileTake it
docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95
lines 1–71why, one step back1---2id: async3title: Async producers & createDraft / finishDraft4sidebar_label: Async produce / createDraft5---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>3435It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:3637```javascript38import produce from "immer"3940const user = {41 name: "michel",42 todos: []43}4445const loadedUser = await produce(user, async function(draft) {46 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()47})48```4950_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._5152## `createDraft` and `finishDraft`5354`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. We could for example rewrite our above example as:5556```javascript57import {createDraft, finishDraft} from "immer"5859const user = {60 name: "michel",61 todos: []62}6364const draft = createDraft(user)65draft.todos = await (await window.fetch("http://host/" + draft.name)).json()66const loadedUser = finishDraft(draft)67```6869Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.7071_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._