Skip to content
Myr

produce.md

This file

Path

docs/produce.md

61 lines · 1.7 KiB · Markdown

Last changed by

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–7why, one step back
1---
2id: produce3title: Using produce4---56<div id="codefund"><!-- fallback content --></div>7

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 8–11why, one step back
8<details>
9 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 3: Simplifying deep updates with _produce_</summary>10 <br>11 <div style="padding:5px;">

docs: fix video player scrolling on chrome, fixes #520Michel Weststratebefore adoptionfbae585

line 12why, one step back
12 <iframe style="border: none;" width=760 height=427 scrolling="no" src="https://egghead.io/lessons/javascript-simplify-deep-state-updates-using-immer-produce/embed" ></iframe>

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

lines 13–16why, one step back
13 </div>
14 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/javascript-simplify-deep-state-updates-using-immer-produce">Hosted on egghead.io</a>15</details>16

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 17–61why, one step back
17The Immer package exposes a default function that does all the work.
1819`produce(currentState, producer: (draftState) => void): nextState`2021There is also a curried overload that is explained [in a later section](curried-produce).2223## Example2425```javascript26import produce from "immer"2728const baseState = [29 {30 todo: "Learn typescript",31 done: true32 },33 {34 todo: "Try immer",35 done: false36 }37]3839const nextState = produce(baseState, draftState => {40 draftState.push({todo: "Tweet about it"})41 draftState[1].done = true42})43```4445The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.4647```javascript48// the new item is only added to the next state,49// base state is unmodified50expect(baseState.length).toBe(2)51expect(nextState.length).toBe(3)5253// same for the changed 'done' prop54expect(baseState[1].done).toBe(false)55expect(nextState[1].done).toBe(true)5657// unchanged data is structurally shared58expect(nextState[0]).toBe(baseState[0])59// changed data not (dûh)60expect(nextState[1]).not.toBe(baseState[1])61```