Skip to content
Myr

return.mdx

This file

Path

website/docs/return.mdx

152 lines · 4.8 KiB

Last changed by

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

History of this file

Take it

The walk stopped after 200 commits: lines older than 07f5cc9 point at it.

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 1–11why, one step back
1---
2id: return3title: Returning new data from producers4---56<center>7 <div8 data-ea-publisher="immerjs"9 data-ea-type="image"10 className="horizontal bordered"11 ></div>

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

lines 12–13why, one step back
12</center>
13<details>

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 14–98why, one step back
14 <summary className="egghead-summary">
15 egghead.io lesson 9: Returning completely new state16 </summary>17 <br />18 <div>19 <iframe20 width="760"21 height="427"22 scrolling="no"23 src="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer/embed"24 ></iframe>25 </div>26 <a27 className="egghead-link"28 href="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer"29 >30 Hosted on egghead.io31 </a>32</details>3334It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway. However, it is allowed to just `return draft`.3536It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft. This can be useful to produce an entirely new state. Some examples:3738```javascript39const userReducer = produce((draft, action) => {40 switch (action.type) {41 case "renameUser":42 // OK: we modify the current state43 draft.users[action.payload.id].name = action.payload.name44 return draft // same as just 'return'45 case "loadUsers":46 // OK: we return an entirely new state47 return action.payload48 case "adduser-1":49 // NOT OK: This doesn't do change the draft nor return a new state!50 // It doesn't modify the draft (it just redeclares it)51 // In fact, this just doesn't do anything at all52 draft = {users: [...draft.users, action.payload]}53 return54 case "adduser-2":55 // NOT OK: modifying draft *and* returning a new state56 draft.userCount += 157 return {users: [...draft.users, action.payload]}58 case "adduser-3":59 // OK: returning a new state. But, unnecessary complex and expensive60 return {61 userCount: draft.userCount + 1,62 users: [...draft.users, action.payload]63 }64 case "adduser-4":65 // OK: the immer way66 draft.userCount += 167 draft.users.push(action.payload)68 return69 }70})71```7273_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._7475## Producing `undefined` using `nothing`7677So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft. There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:7879```javascript80produce({}, draft => {81 // don't do anything82})83```8485Versus:8687```javascript88produce({}, draft => {89 // Try to return undefined from the producer90 return undefined91})92```9394The problem is that in JavaScript a function that doesn't return anything also returns `undefined`! So immer cannot differentiate between those different cases. So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.9596However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:9798```javascript

Merge pull request #1028 from immerjs/immer-10Michel Weststratebefore adoption2ef9a42

line 99why, one step back
99import {produce, nothing} from "immer"

chore(test): fix production build unit testsMichel Weststratebefore adoption07f5cc9

lines 100–152why, one step back
100
101const state = {102 hello: "world"103}104105produce(state, draft => {})106produce(state, draft => undefined)107// Both return the original state: { hello: "world"}108109produce(state, draft => nothing)110// Produces a new state, 'undefined'111```112113N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.114115Tip: to be able to return `nothing` from a recipe when using TypeScript, the `state`'s type must accept `undefined` as value.116117## Inline shortcuts using `void`118119<details>120 <summary className="egghead-summary">121 egghead.io lesson 10: Avoid accidental returns by using _void_122 </summary>123 <br />124 <div>125 <iframe126 width="760"127 height="427"128 scrolling="no"129 src="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword/embed"130 ></iframe>131 </div>132 <a133 className="egghead-link"134 href="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword"135 >136 Hosted on egghead.io137 </a>138</details>139140Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.141142In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.143144```javascript145// Single mutation146produce(draft => void (draft.user.age += 1))147148// Multiple mutations149produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))150```151152Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.