Skip to content
Myr

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

7 files+100 added−8 removed

modified:__tests__/base.js+18 added-1 removed
1"use strict"2import produce, {setAutoFreeze, setUseProxies} from "../src/immer"2import produce, {setAutoFreeze, setUseProxies, nothing} from "../src/immer"3import deepFreeze from "deep-freeze"4import cloneDeep from "lodash.clonedeep"5import * as lodash from "lodash"6
1267 unmodified lines
1274 )1275 })1276 })12771278 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)12851286 expect(produce({}, () => undefined)).toEqual({})1287 expect(produce({}, () => nothing)).toBe(undefined)1288 expect(produce(3, () => nothing)).toBe(undefined)12891290 expect(produce(() => undefined)({})).toEqual({})1291 expect(produce(() => nothing)({})).toBe(undefined)1292 expect(produce(() => nothing)(3)).toBe(undefined)1293 })12941295 afterEach(() => {1296 expect(baseState).toBe(origBaseState)1297 expect(baseState).toEqual(createBaseState())1298 })
21 unmodified lines
modified:src/common.js+5 added
modified:src/immer.d.ts+2 added
93 unmodified lines
9495export const produce: IProduce96export default produce9798export const nothing: undefined99100/**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 lines
modified:src/immer.js+15 added-5 removed
1export {setAutoFreeze, setUseProxies, original} from "./common"23import {applyPatches as applyPatchesImpl} from "./patches"4import {isProxyable, getUseProxies} from "./common"4import {isProxyable, getUseProxies, NOTHING} from "./common"5import {produceProxy} from "./proxy"6import {produceEs5} from "./es5"78/**
42 unmodified lines
5152 // 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 }5960 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}7071function normalizeResult(result) {72 return result === NOTHING ? undefined : result73}7475export default produce7677export const applyPatches = produce(applyPatchesImpl)7879export const nothing = NOTHING
modified:src/immer.js.flow+2 added
67 unmodified lines
6869declare export var produce: IProduce70declare export default IProduce7172declare export var nothing: undefined7374/**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 lines
modified:changelog.md+4 added
1# Changelog23### 1.7.045* 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).67### 1.6.089* 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 lines
modified:readme.md+54 added-2 removed
351 unmodified lines
352 }353})354```355356_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..._357358## Producing `undefined` using `nothing`359360So, in general one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft.361There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:362363```javascript364produce({}, draft => {365 // don't do anything366})367```368369Versus:370371```javascript372produce({}, draft => {373 // Try to return undefined from the producer374 return undefined375})376```377378The problem is that in JavaScript a function that doesn't return anything, also returns `undefined`!379So immer cannot differentiate between those different cases.380So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.381382However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:383384```javascript385import produce, { nothing } from "immer"386387const state = {388 hello: "world"389}390391produce(state, (draft) => {392 // no-op393})394// Returns the original state: { hello: "world"}395396produce(state, (draft) => undefined)397// Returns the original state: { hello: "world"}398399produce(state, (draft) => {400 return nothing401})402// Produces a new state, 'undefined'403404produce(state, (draft) => nothing)405// Produces a new state, 'undefined'406```407408N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.409410## Extracting the original object from a proxied instance411412Immer 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 lines
5211. 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.5221. 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.5231. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.5241. 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)})`4731. 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!5251. 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.5261. 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:527528```javascript529const state = {
159 unmodified lines