Skip to content
Myr

produce.mdx

This file

Path

website/docs/produce.mdx

92 lines · 3.1 KiB

Last changed by

docs: add typed custom produce function (#1239)Dean Kerrbefore adoption955c5f5

History of this file

Take it

1---2id: produce3title: Using produce4---56<center>7	<div8		data-ea-publisher="immerjs"9		data-ea-type="image"10		className="horizontal bordered"11	></div>12</center> <details>13	<summary className="egghead-summary">14		egghead.io lesson 3: Simplifying deep updates with _produce_15	</summary>16	<br />17	<div>18		<iframe19			width="760"20			height="427"21			scrolling="no"22			src="https://egghead.io/lessons/javascript-simplify-deep-state-updates-using-immer-produce/embed"23		></iframe>24	</div>25	<a26		className="egghead-link"27		href="https://egghead.io/lessons/javascript-simplify-deep-state-updates-using-immer-produce"28	>29		Hosted on egghead.io30	</a>31</details>3233The Immer package exposes a `produce` function that does all the work.3435`produce(baseState, recipe: (draftState) => void): nextState`3637`produce` takes a base state, and a _recipe_ that can be used to perform all the desired mutations on the `draft` that is passed in. The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.3839Inside the recipe, all standard JavaScript APIs can be used on the `draft` object, including field assignments, `delete` operations, and mutating array, Map and Set operations like `push`, `pop`, `splice`, `set`, `sort`, `remove`, etc.4041Any of those mutations don't have to happen at the root, but it is allowed to modify anything anywhere deep inside the draft: `draft.todos[0].tags["urgent"].author.age = 56`4243Note that the recipe function itself normally doesn't return anything. However, it is possible to return in case you want to replace the `draft` object in its entirety with another object, for more details see [returning new data](./return.mdx).4445## Example4647```javascript48import {produce} from "immer"4950const baseState = [51	{52		title: "Learn TypeScript",53		done: true54	},55	{56		title: "Try Immer",57		done: false58	}59]6061const nextState = produce(baseState, draftState => {62	draftState.push({title: "Tweet about it"})63	draftState[1].done = true64})65```6667```javascript68// the new item is only added to the next state,69// base state is unmodified70expect(baseState.length).toBe(2)71expect(nextState.length).toBe(3)7273// same for the changed 'done' prop74expect(baseState[1].done).toBe(false)75expect(nextState[1].done).toBe(true)7677// unchanged data is structurally shared78expect(nextState[0]).toBe(baseState[0])79// ...but changed data isn't.80expect(nextState[1]).not.toBe(baseState[1])81```8283For advanced TypeScript typing scenarios, see [Using TypeScript or Flow](./typescript.mdx).8485### Terminology8687- `(base)state`, the immutable state passed to `produce`88- `recipe`: the second argument of `produce`, that captures how the base state should be "mutated".89- `draft`: the first argument of any `recipe`, which is a proxy to the original base state that can be safely mutated.90- `producer`. A function that uses `produce` and is generally of the form `(baseState, ...arguments) => resultState`9192Note that it isn't strictly necessary to name the first argument of the recipe `draft`. You can name it anything you want, for example `users`. Using `draft` as a name is just a convention to signal: "mutation is OK here".