Skip to content
Myr

return.mdx

This file

Path

website/docs/return.mdx

151 lines · 4.8 KiB

Last changed by

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

History of this file

Take it

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

fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173

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>

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

line 12why, one step back
12</center> <details>

fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173

lines 13–97why, one step back
13 <summary className="egghead-summary">
14 egghead.io lesson 9: Returning completely new state15 </summary>16 <br />17 <div>18 <iframe19 width="760"20 height="427"21 scrolling="no"22 src="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer/embed"23 ></iframe>24 </div>25 <a26 className="egghead-link"27 href="https://egghead.io/lessons/react-return-completely-new-state-from-an-immer-producer"28 >29 Hosted on egghead.io30 </a>31</details>3233It 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`.3435It 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:3637```javascript38const userReducer = produce((draft, action) => {39 switch (action.type) {40 case "renameUser":41 // OK: we modify the current state42 draft.users[action.payload.id].name = action.payload.name43 return draft // same as just 'return'44 case "loadUsers":45 // OK: we return an entirely new state46 return action.payload47 case "adduser-1":48 // NOT OK: This doesn't do change the draft nor return a new state!49 // It doesn't modify the draft (it just redeclares it)50 // In fact, this just doesn't do anything at all51 draft = {users: [...draft.users, action.payload]}52 return53 case "adduser-2":54 // NOT OK: modifying draft *and* returning a new state55 draft.userCount += 156 return {users: [...draft.users, action.payload]}57 case "adduser-3":58 // OK: returning a new state. But, unnecessary complex and expensive59 return {60 userCount: draft.userCount + 1,61 users: [...draft.users, action.payload]62 }63 case "adduser-4":64 // OK: the immer way65 draft.userCount += 166 draft.users.push(action.payload)67 return68 }69})70```7172_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._7374## Producing `undefined` using `nothing`7576So, 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`:7778```javascript79produce({}, draft => {80 // don't do anything81})82```8384Versus:8586```javascript87produce({}, draft => {88 // Try to return undefined from the producer89 return undefined90})91```9293The 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.9495However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:9697```javascript

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

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

fix: #785 fix type inference for produce incorrectly inferring promise (#786)hardfistbefore adoption6555173

lines 99–151why, one step back
99
100const state = {101 hello: "world"102}103104produce(state, draft => {})105produce(state, draft => undefined)106// Both return the original state: { hello: "world"}107108produce(state, draft => nothing)109// Produces a new state, 'undefined'110```111112N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.113114Tip: to be able to return `nothing` from a recipe when using TypeScript, the `state`'s type must accept `undefined` as value.115116## Inline shortcuts using `void`117118<details>119 <summary className="egghead-summary">120 egghead.io lesson 10: Avoid accidental returns by using _void_121 </summary>122 <br />123 <div>124 <iframe125 width="760"126 height="427"127 scrolling="no"128 src="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword/embed"129 ></iframe>130 </div>131 <a132 className="egghead-link"133 href="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword"134 >135 Hosted on egghead.io136 </a>137</details>138139Draft 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.140141In 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`.142143```javascript144// Single mutation145produce(draft => void (draft.user.age += 1))146147// Multiple mutations148produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))149```150151Code 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.