return.md
This file
Path
docs/return.md
121 lines · 4.8 KiB · Markdown
Last changed by
Added egghead.io video embedsMichel Weststratebefore adoptiona866760
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–7why, one step back1---2id: return3title: Returning new data from producers4---56<div id="codefund"><!-- fallback content --></div>7Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 8–16why, one step back8<details>9 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 9: Returning completely new state</summary>10 <br>11 <div style="padding:5px;">12 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer/embed" ></iframe>13 </div>14 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer">Hosted on egghead.io</a>15</details>16Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 17–98why, one step back17It 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`.1819It 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:2021```javascript22const userReducer = produce((draft, action) => {23 switch (action.type) {24 case "renameUser":25 // OK: we modify the current state26 draft.users[action.payload.id].name = action.payload.name27 return draft // same as just 'return'28 case "loadUsers":29 // OK: we return an entirely new state30 return action.payload31 case "adduser-1":32 // NOT OK: This doesn't do change the draft nor return a new state!33 // It doesn't modify the draft (it just redeclares it)34 // In fact, this just doesn't do anything at all35 draft = {users: [...draft.users, action.payload]}36 return37 case "adduser-2":38 // NOT OK: modifying draft *and* returning a new state39 draft.userCount += 140 return {users: [...draft.users, action.payload]}41 case "adduser-3":42 // OK: returning a new state. But, unnecessary complex and expensive43 return {44 userCount: draft.userCount + 1,45 users: [...draft.users, action.payload]46 }47 case "adduser-4":48 // OK: the immer way49 draft.userCount += 150 draft.users.push(action.payload)51 return52 }53})54```5556_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._5758## Producing `undefined` using `nothing`5960So, 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`:6162```javascript63produce({}, draft => {64 // don't do anything65})66```6768Versus:6970```javascript71produce({}, draft => {72 // Try to return undefined from the producer73 return undefined74})75```7677The 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.7879However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:8081```javascript82import produce, {nothing} from "immer"8384const state = {85 hello: "world"86}8788produce(state, draft => {})89produce(state, draft => undefined)90// Both return the original state: { hello: "world"}9192produce(state, draft => nothing)93// Produces a new state, 'undefined'94```9596N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.9798## Inline shortcuts using `void`Added egghead.io video embedsMichel Weststratebefore adoptiona866760
lines 99–107why, one step back99100<details>101 <summary style="color: white; background:#c200c2;padding:5px;margin:5px;border-radius:2px">egghead.io lesson 10: Avoid accidental returns by using _void_</summary>102 <br>103 <div style="padding:5px;">104 <iframe style="border: none;" width=760 height=427 src="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword/embed" ></iframe>105 </div>106 <a style="font-style:italic;padding:5px;margin:5px;" href="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword">Hosted on egghead.io</a>107</details>Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 108–121why, one step back108109Draft 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.110111In 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`.112113```javascript114// Single mutation115produce(draft => void (draft.user.age += 1))116117// Multiple mutations118produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))119```120121Code 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.