Skip to content
Myr

produce.md

This file

Path

docs/produce.md

63 lines · 1.8 KiB · Markdown

Last changed by

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

History of this file

Take it

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 1–5why, one step back
1---
2id: produce3title: Using produce4---5

docs: updated sponsor linksMichel Weststratebefore adoptionf97d037

lines 6–8why, one step back
6<center>
7<div data-ea-publisher="immerjs" data-ea-type="image" class="horizontal bordered"></div>8</center>

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

line 9why, one step back
9

Added egghead.io video embedsMichel Weststratebefore adoptiona866760

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

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

line 14why, one step back
14 <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 15–18why, one step back
15 </div>
16 <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>17</details>18

Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46

lines 19–63why, one step back
19The Immer package exposes a default function that does all the work.
2021`produce(currentState, producer: (draftState) => void): nextState`2223There is also a curried overload that is explained [in a later section](curried-produce).2425## Example2627```javascript28import produce from "immer"2930const baseState = [31 {32 todo: "Learn typescript",33 done: true34 },35 {36 todo: "Try immer",37 done: false38 }39]4041const nextState = produce(baseState, draftState => {42 draftState.push({todo: "Tweet about it"})43 draftState[1].done = true44})45```4647The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.4849```javascript50// the new item is only added to the next state,51// base state is unmodified52expect(baseState.length).toBe(2)53expect(nextState.length).toBe(3)5455// same for the changed 'done' prop56expect(baseState[1].done).toBe(false)57expect(nextState[1].done).toBe(true)5859// unchanged data is structurally shared60expect(nextState[0]).toBe(baseState[0])61// changed data not (dûh)62expect(nextState[1]).not.toBe(baseState[1])63```