Introduced the concept of `nothing`
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Michel Weststrate · committed by Michel Weststrate · parent 4f27a93 · Browse files · 7 files·+100 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+100 added−8 removed
- tests:+18 added−1 removed
- other:+82 added−7 removed
Provenance
- Commit
798d2b2- Tree
105ce56- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
4f27a93
7 files changed+100 added−8 removed
modified:__tests__/base.js+18 added-1 removed
1 "use strict"2-import produce, {setAutoFreeze, setUseProxies} from "../src/immer"2+import produce, {setAutoFreeze, setUseProxies, nothing} from "../src/immer"3 import deepFreeze from "deep-freeze"4 import cloneDeep from "lodash.clonedeep"5 import * as lodash from "lodash"6 1267 unmodified lines1274 )1275 })1276 })1277 1278+ it("cannot return and produce undefined!", () => {1279+ const base = 31280+ expect(produce(base, () => 4)).toBe(4)1281+ expect(produce(base, () => null)).toBe(null)1282+ expect(produce(base, () => undefined)).toBe(3)1283+ expect(produce(base, () => {})).toBe(3)1284+ expect(produce(base, () => nothing)).toBe(undefined)1285+1286+ expect(produce({}, () => undefined)).toEqual({})1287+ expect(produce({}, () => nothing)).toBe(undefined)1288+ expect(produce(3, () => nothing)).toBe(undefined)1289+1290+ expect(produce(() => undefined)({})).toEqual({})1291+ expect(produce(() => nothing)({})).toBe(undefined)1292+ expect(produce(() => nothing)(3)).toBe(undefined)1293+ })1294+1295 afterEach(() => {1296 expect(baseState).toBe(origBaseState)1297 expect(baseState).toEqual(createBaseState())1298 })21 unmodified linesmodified:src/common.js+5 added
1234567891011169 unmodified linesExpand allimport {generatePatches} from "./patches"
export const NOTHING = typeof Symbol !== "undefined" ? Symbol("immer-nothing") : {["immer-nothing"]: true}
export const PROXY_STATE = typeof Symbol !== "undefined" ? Symbol("immer-proxy-state") : "__$immer_state"169 unmodified linesExpand allmodified:src/immer.d.ts+2 added
93 unmodified lines94 95 export const produce: IProduce96 export default produce97 98+export const nothing: undefined99+100 /**101 * Automatically freezes any state trees generated by immer.102 * This protects against accidental modifications of the state tree outside of an immer function.103 * This comes with a performance impact, so it is recommended to disable this option in production.13 unmodified linesmodified:src/immer.js+15 added-5 removed
1 export {setAutoFreeze, setUseProxies, original} from "./common"2 3 import {applyPatches as applyPatchesImpl} from "./patches"4-import {isProxyable, getUseProxies} from "./common"4+import {isProxyable, getUseProxies, NOTHING} from "./common"5 import {produceProxy} from "./proxy"6 import {produceEs5} from "./es5"7 8 /**42 unmodified lines51 52 // if state is a primitive, don't bother proxying at all53 if (typeof baseState !== "object" || baseState === null) {54 const returnValue = producer(baseState)55- return returnValue === undefined ? baseState : returnValue55+ return returnValue === undefined56+ ? baseState57+ : normalizeResult(returnValue)58 }59 60 if (!isProxyable(baseState))61 throw new Error(62 `the first argument to an immer producer should be a primitive, plain object or array, got ${typeof baseState}: "${baseState}"`63 )64+ return normalizeResult(62- return getUseProxies()63- ? produceProxy(baseState, producer, patchListener)64- : produceEs5(baseState, producer, patchListener)65+ getUseProxies()66+ ? produceProxy(baseState, producer, patchListener)67+ : produceEs5(baseState, producer, patchListener)68+ )69 }70 71+function normalizeResult(result) {72+ return result === NOTHING ? undefined : result73+}74+75 export default produce76 77 export const applyPatches = produce(applyPatchesImpl)78+79+export const nothing = NOTHINGmodified:src/immer.js.flow+2 added
67 unmodified lines68 69 declare export var produce: IProduce70 declare export default IProduce71 72+declare export var nothing: undefined73+74 /**75 * Automatically freezes any state trees generated by immer.76 * This protects against accidental modifications of the state tree outside of an immer function.77 * This comes with a performance impact, so it is recommended to disable this option in production.13 unmodified linesmodified:changelog.md+4 added
1 # Changelog2 3+### 1.7.04+5+* Introduced the [`nothing`](https://github.com/mweststrate/immer#producing-undefined-using-nothing) token to be able to produce the `undefined` value (which would otherwise be indistinguishable from not updating the draft at all).6+7 ### 1.6.08 9 * Introduced the `original(draft)` function, that, given an object from the draft, returns the original object from the base state. This can be useful if you need to do reference equality checks, or comparisons with the base state. See [#179](https://github.com/mweststrate/immer/pull/179) by [@RichieAHB](https://github.com/RichieAHB).10 * Writing or removing non-numeric properties on arrays is now strictly forbidden (Immer didn't throw before, but correct behavior wasn't guaranteed either)170 unmodified linesmodified:readme.md+54 added-2 removed
351 unmodified lines352 }353 })354 ```355 356-_Note: It is not possible to return `undefined` this way, as it is indistiguishable from updating the draft!_356+_Note: It is not possible to return `undefined` this way, as it is indistiguishable from *not* updating the draft! Read on..._357 358+## Producing `undefined` using `nothing`359+360+So, in general one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.361+There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:362+363+```javascript364+produce({}, draft => {365+ // don't do anything366+})367+```368+369+Versus:370+371+```javascript372+produce({}, draft => {373+ // Try to return undefined from the producer374+ return undefined375+})376+```377+378+The problem is that in JavaScript a function that doesn't return anything, also returns `undefined`!379+So immer cannot differentiate between those different cases.380+So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.381+382+However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:383+384+```javascript385+import produce, { nothing } from "immer"386+387+const state = {388+ hello: "world"389+}390+391+produce(state, (draft) => {392+ // no-op393+})394+// Returns the original state: { hello: "world"}395+396+produce(state, (draft) => undefined)397+// Returns the original state: { hello: "world"}398+399+produce(state, (draft) => {400+ return nothing401+})402+// Produces a new state, 'undefined'403+404+produce(state, (draft) => nothing)405+// Produces a new state, 'undefined'406+```407+408+N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.409+410 ## Extracting the original object from a proxied instance411 412 Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.413 107 unmodified lines521 1. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.522 1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.523 1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.524 1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`473-1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistiguishable from updating the draft!525+1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistiguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.526 1. Immer does not support built in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:527 528 ```javascript529 const state = {159 unmodified lines