Implemented and document #108: allow returning values from producers
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 2c8a71a · Browse files · 8 files·+134 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+134 added−34 removed
- tests:+41 added−14 removed
- other:+93 added−20 removed
Provenance
- Commit
c589ddd- Tree
da6a32a- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
2c8a71a
8 files changed+134 added−34 removed
modified:__tests__/base.js+38 added-11 removed
33 unmodified lines34 })35 expect(nextState).toBe(baseState)36 })37 38- it("should not return any value: thunk", () => {39- const warning = jest.spyOn(console, "warn")40- produce(baseState, () => ({bad: "don't do this"}))41- produce(baseState, () => [1, 2, 3])42- produce(baseState, () => false)43- produce(baseState, () => "")44-45- expect(warning).toHaveBeenCalledTimes(4)46- warning.mockClear()47- })48-38 it("should return a copy when modifying stuff", () => {39 const nextState = produce(baseState, s => {40 s.aProp = "hello world"41 })769 unmodified lines811 expect(base[0].a).toEqual(1)812 expect(result[0].a).toEqual(2)813 })814 815+ it("can produce from no state", () => {816+ expect(817+ produce(3, draft => {818+ expect(draft).toBe(3)819+ return 5820+ })821+ ).toBe(5)822+ })823+824+ it("can return something new ", () => {825+ const base = {x: 3}826+ const res = produce(base, draft => {827+ return {x: draft.x + 1}828+ })829+ expect(res).not.toBe(base)830+ expect(res).toEqual({x: 4})831+ })832+833+ it("can return the draft new ", () => {834+ const base = {x: 3}835+ const res = produce(base, draft => {836+ draft.x = 4837+ return draft838+ })839+ expect(res).not.toBe(base)840+ expect(res).toEqual({x: 4})841+ })842+843+ it("should throw if modifying the draft and returning something new", () => {844+ const base = {x: 3}845+ expect(() => {846+ produce(base, draft => {847+ draft.x = 4848+ return {x: 5}849+ })850+ }).toThrow(/An immer producer returned a new value/)851+ })852+853 afterEach(() => {854 expect(baseState).toBe(origBaseState)855 expect(baseState).toEqual(createBaseState())856 })21 unmodified linesmodified:__tests__/curry.js+3 added-3 removed
9 unmodified lines10111213141415161716171819202122 unmodified lines9 unmodified lines
it("should check arguments", () => { expect(() => produce()).toThrow(/produce expects 1 or 2 arguments/) expect(() => produce(() => {}, {})).toThrow( /the first argument to produce should be a plain object or array/ /the second argument to produce should be a function/ ) expect(() => produce(1, () => {})).toThrow( /the first argument to produce should be a plain object or array/ expect(() => produce(new Buffer(""), () => {})).toThrow( /the first argument to an immer producer should be a primitive, plain object or array/ ) expect(() => produce({}, () => {}, [])).toThrow( /produce expects 1 or 2 arguments/ )22 unmodified linesmodified:src/common.js+12 added-7 removed
123456789101112131114151617181993 unmodified lines1131141151161141151161171181191171181191201211221231241251261271286 unmodified linesexport const PROXY_STATE = typeof Symbol !== "undefined" ? Symbol("immer-proxy-state") : "__$immer_state"
export const RETURNED_AND_MODIFIED_ERROR = "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft."
function verifyMinified() {}
const inProduction = (typeof process !== "undefined" && process.env.NODE_ENV === "production") || verifyMinified.name !== "verifyMinified"let autoFreeze = !inProduction
let autoFreeze = !inProductionlet useProxies = typeof Proxy !== "undefined"
/** * Automatically freezes any state trees generated by immer.93 unmodified lines // always freeze completely new data freeze(parent)}
export function verifyReturnValue(value) { // values either than undefined will trigger warning; if (value !== undefined) console.warn( `Immer callback expects no return value. However ${typeof value} was returned` )export function verifyReturnValue(returnedValue, proxy, isProxyModified) { if (returnedValue !== undefined && returnedValue !== proxy) { // something was returned, and it wasn't the proxy itself if (isProxyModified) throw new Error( "An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft." ) }}
export function is(x, y) { // From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js6 unmodified linesmodified:src/es5.js+12 added-5 removed
6 unmodified lines7 isProxy,8 freeze,9 PROXY_STATE,10 shallowCopy,11- verifyReturnValue,11+ RETURNED_AND_MODIFIED_ERROR,12 each,13 finalize14 } from "./common"15 119 unmodified lines135 const prevStates = states136 states = []137 try {138 // create proxy for root139- const rootClone = createProxy(undefined, baseState)139+ const rootProxy = createProxy(undefined, baseState)140 // execute the thunk141- verifyReturnValue(producer.call(rootClone, rootClone))141+ const returnValue = producer.call(rootProxy, rootProxy)142 // and finalize the modified proxy143 each(states, (_, state) => {144 state.finalizing = true145 })146 // find and mark all changes (for parts not done yet)147 // TODO: store states by depth, to be able guarantee processing leaves first148 markChanges()149- const res = finalize(rootClone)149+ let result = finalize(rootProxy)150+ // check whether the draft was modified and/or a value was returned151+ if (returnValue !== undefined && returnValue !== rootProxy) {152+ // something was returned, and it wasn't the proxy itself153+ if (rootProxy[PROXY_STATE].modified)154+ throw new Error(RETURNED_AND_MODIFIED_ERROR)155+ result = returnValue156+ }157 // make sure all proxies become unusable158 each(states, (_, state) => {159 state.finished = true160 })154- return res161+ return result162 } finally {163 states = prevStates164 }165 }33 unmodified linesmodified:src/immer.js+7 added-1 removed
30 unmodified lines31 32 // prettier-ignore33 {34 if (arguments.length !== 2) throw new Error("produce expects 1 or 2 arguments, got " + arguments.length)35- if (!isProxyable(baseState)) throw new Error("the first argument to produce should be a plain object or array, got " + (typeof baseState))35 if (typeof producer !== "function") throw new Error("the second argument to produce should be a function")36 }37 38+ // it state is a primitive, don't bother proxying at all and just return whatever the producer returns on that value39+ if (typeof baseState !== "object" || baseState === null)40+ return producer(baseState)41+ if (!isProxyable(baseState))42+ throw new Error(43+ `the first argument to an immer producer should be a primitive, plain object or array, got ${typeof baseState}: "${baseState}"`44+ )45 return getUseProxies()46 ? produceProxy(baseState, producer)47 : produceEs5(baseState, producer)48 }modified:src/proxy.js+12 added-5 removed
8 unmodified lines9 freeze,10 PROXY_STATE,11 finalize,12 shallowCopy,13- verifyReturnValue,13+ RETURNED_AND_MODIFIED_ERROR,14 each15 } from "./common"16 17 let proxies = null115 unmodified lines133 const previousProxies = proxies134 proxies = []135 try {136 // create proxy for root137- const rootClone = createProxy(undefined, baseState)137+ const rootProxy = createProxy(undefined, baseState)138 // execute the thunk139- verifyReturnValue(producer.call(rootClone, rootClone))139+ const returnValue = producer.call(rootProxy, rootProxy)140 // and finalize the modified proxy141- const res = finalize(rootClone)141+ let result = finalize(rootProxy)142+ // check whether the draft was modified and/or a value was returned143+ if (returnValue !== undefined && returnValue !== rootProxy) {144+ // something was returned, and it wasn't the proxy itself145+ if (rootProxy[PROXY_STATE].modified)146+ throw new Error(RETURNED_AND_MODIFIED_ERROR)147+ result = returnValue148+ }149 // revoke all proxies150 each(proxies, (_, p) => p.revoke())144- return res151+ return result152 } finally {153 proxies = previousProxies154 }155 }modified:changelog.md+5 added-1 removed
1 # Changelog2 3+### 1.1.04+5+* It is now possible to return an entirely new state from a producer as well. Immer will verify that you didn't both change the draft and returned a new state. Implements [#103](https://github.com/mweststrate/immer/issues/103)6+7 ### 1.0.3 (15-Feb-2018)8 5-* Fixed dectection of production mode. Fixes [#95](https://github.com/mweststrate/immer/issues/95)9+* Fixed detection of production mode. Fixes [#95](https://github.com/mweststrate/immer/issues/95)10 11 ### 1.0.2 (13-Feb-2018)12 13 * `flow-bin` and `cpx` were accidentally dependencies instead of dev-dependencies. Fixed119 unmodified linesmodified:readme.md+45 added-1 removed
155 unmodified lines156 }157 158 /**159 * ...But, since setState accepts functions,160- * we can just create curried producer and simplify this!160+ * we can just create a curried producer and further simplify!161 */162 onBirthDayClick2 = () => {163 this.setState(produce(draft => {164 draft.user.age += 147 unmodified lines212 It is by default enabled.213 By default it is turned on during local development, and turned off in production.214 Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.215 216+## Returning data from producers217+218+It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway.219+However, it allowed to just `return draft`.220+221+It is also allowed to return abritrarily other data from the producer function. But _only_ if you didn't modify the draft.222+This can be useful to produce an entirely new state. Some examples:223+224+```javascript225+const userReducer = produce((draft, action) => {226+ switch (action.type) {227+ case "renameUser":228+ // OK: we modify the current state229+ draft.users[action.payload.id].name = action.payload.name230+ return draft // same as just 'return'231+ case "loadUsers":232+ // OK: we return an entirely new state233+ return action.payload234+ case "adduser-1":235+ // NOT OK: This doesn't do change the draft nor return a new state!236+ // It doesn't modify the draft (it just redeclares it)237+ // In fact, this just doesn't do anything at all238+ draft = { users: [...draft.users, action.payload]}239+ return240+ case "adduser-2":241+ // NOT OK: modifying draft *and* returning a new state242+ draft.userCount += 1243+ return { users: [...draft.users, action.payload] }244+ case "adduser-3":245+ // OK: returning a new state. But, unnecessary complex and expensive246+ return {247+ userCount: draft.userCount + 1,248+ users: [...draft.users, action.payload]249+ }250+ case "adduser-4":251+ // OK: the immer way252+ draft.userCount += 1253+ draft.push(action.payload)254+ return255+ }256+})257+```258+259 ## Using `this`260 261 The recipe will be always invoked with the `draft` as `this` context.262 26 unmodified lines289 In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.290 291 ## Pitfalls292 293+1. Don't redefine draft like, `draft = myCoolNewState`. Instead, either modify the `draft` or return a new state. See [Returning data from producers](#returning-data-from-producers).294 1. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.295 2. Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` (or whatever complex object from the draft state), the changes will be persisted. But, both in your new and old state! So, in such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.296 3. 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.297 4. 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`70 unmodified lines