Skip to content
Myr

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

8 files+134 added−34 removed

modified:__tests__/base.js+38 added-11 removed
33 unmodified lines
34 })35 expect(nextState).toBe(baseState)36 })3738 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, () => "")4445 expect(warning).toHaveBeenCalledTimes(4)46 warning.mockClear()47 })4838 it("should return a copy when modifying stuff", () => {39 const nextState = produce(baseState, s => {40 s.aProp = "hello world"41 })
769 unmodified lines
811 expect(base[0].a).toEqual(1)812 expect(result[0].a).toEqual(2)813 })814815 it("can produce from no state", () => {816 expect(817 produce(3, draft => {818 expect(draft).toBe(3)819 return 5820 })821 ).toBe(5)822 })823824 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 })832833 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 })842843 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 })852853 afterEach(() => {854 expect(baseState).toBe(origBaseState)855 expect(baseState).toEqual(createBaseState())856 })
21 unmodified lines
modified:__tests__/curry.js+3 added-3 removed
modified:src/common.js+12 added-7 removed
modified:src/es5.js+12 added-5 removed
6 unmodified lines
7 isProxy,8 freeze,9 PROXY_STATE,10 shallowCopy,11 verifyReturnValue,11 RETURNED_AND_MODIFIED_ERROR,12 each,13 finalize14} from "./common"15
119 unmodified lines
135 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 lines
modified:src/immer.js+7 added-1 removed
30 unmodified lines
3132 // 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 }3738 // 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 lines
9 freeze,10 PROXY_STATE,11 finalize,12 shallowCopy,13 verifyReturnValue,13 RETURNED_AND_MODIFIED_ERROR,14 each15} from "./common"1617let proxies = null
115 unmodified lines
133 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# Changelog23### 1.1.045* 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)67### 1.0.3 (15-Feb-2018)85* 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)1011### 1.0.2 (13-Feb-2018)1213* `flow-bin` and `cpx` were accidentally dependencies instead of dev-dependencies. Fixed
119 unmodified lines
modified:readme.md+45 added-1 removed
155 unmodified lines
156}157158/**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*/162onBirthDayClick2 = () => {163 this.setState(produce(draft => {164 draft.user.age += 1
47 unmodified lines
212 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.215216## Returning data from producers217218It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway.219However, it allowed to just `return draft`.220221It is also allowed to return abritrarily other data from the producer function. But _only_ if you didn't modify the draft.222This can be useful to produce an entirely new state. Some examples:223224```javascript225const 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```258259## Using `this`260261The recipe will be always invoked with the `draft` as `this` context.262
26 unmodified lines
289In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.290291## Pitfalls2922931. 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).2941. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.2952. 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.2963. 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.2974. 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