Skip to content
Myr

return.mdx

This file

Path

website/docs/return.mdx

149 lines · 4.7 KiB

Last changed by

docs: Update to docusaurus 2Michel Weststratebefore adoption42aac95

History of this file

Take it

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>12</center> <details>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```javascript98import produce, {nothing} from "immer"99100const 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.113114## Inline shortcuts using `void`115116<details>117	<summary className="egghead-summary">118		egghead.io lesson 10: Avoid accidental returns by using _void_119	</summary>120	<br />121	<div>122		<iframe123			width="760"124			height="427"125			scrolling="no"126			src="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword/embed"127		></iframe>128	</div>129	<a130		className="egghead-link"131		href="https://egghead.io/lessons/react-avoid-accidental-returns-of-new-state-by-using-the-void-keyword"132	>133		Hosted on egghead.io134	</a>135</details>136137Draft 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.138139In 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`.140141```javascript142// Single mutation143produce(draft => void (draft.user.age += 1))144145// Multiple mutations146produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))147```148149Code 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.