Merge branch 'master' into kachkaev-add-failing-tests-for-recursive-use
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 · parents 3069aaa, 41bb8b9 · Browse files · 12 files·+214 added−189 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+214 added−189 removed
- tests:+52 added−20 removed
- other:+162 added−169 removed
Provenance
- Commit
f7b9bfe- Tree
48a8b93- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent 1
3069aaa- Parent 2
41bb8b9
12 files changed+214 added−189 removed
modified:__tests__/flow/flow.js.flow+24 added-10 removed
12 unmodified lines13 })14 15 console.log(result.x)16 17-const f2 = produce(draft => {})17+const result2 = produce({x: 3}, draft => {18+ return {x: 4}19+})20+21+console.log(result2.x)22+23+const f = produce((draft): {x: number} => {24+ return {x: 4}25+})26+f({x: 3})27+28+const f2 = produce((draft): void => {})29 f2({x: 3})30 31 // $ExpectError32 setAutoFreeze(3)11 unmodified lines44 produce({x: 3}, [])45 46 {47 // curried & initial arg37- const f = produce((state, increment: number) => {38- state.x += increment39- }, { x: 3})48+ const f = produce(49+ (state, increment: number): void => {50+ state.x += increment51+ },52+ {x: 3}53+ )54 55 // $ExpectError Too few arguments42- f({x : 5})56+ f({x: 5})57 58 // $ExpectError45- f({x : 5}, "test")59+ f({x: 5}, "test")60 47- f({x : 5}, 3)61+ f({x: 5}, 3)62 63 f(undefined, 3)64 }65 66 {67 // curried f & no initial arg54- const f2 = produce((state: {x:number}, increment: number) => {68+ const f2 = produce((state: {x: number}, increment: number): void => {69 state.x += increment70 })71 58- f2({x : 5}, 3)72+ f2({x: 5}, 3)73 74 // $ExpectError75 f2(undefined, 3)62-}76+}modified:__tests__/flow/ts.ts+27 added-9 removed
31 unmodified lines32333435363637383738394041424341444546444748464950515253545553565758595760616263616465666768697071727374757677787931 unmodified linesproduce({x: 3}, [])
{ // curried & initial arg const f = produce( const f = produce((state, increment: number) => { state.x += increment }, { x: 3}) (state, increment: number) => { state.x += increment }, {x: 3} )
// $ExpectError Too few arguments f({x : 5}) f({x: 5})
// $ExpectError f({x : 5}, "test") f({x: 5}, "test")
f({x : 5}, 3) f({x: 5}, 3)
f(undefined, 3)}
{ // curried f & no initial arg const f2 = produce((state: {x:number}, increment: number) => { const f2 = produce((state: {x: number}, increment: number) => { state.x += increment })
f2({x : 5}, 3) f2({x: 5}, 3)
// $ExpectError f2(undefined, 3)}No newline at end of file}
{ // Issue #129 const handlers = { ["TEST"]: (draft: {}, {id, value}: {id: string; value: string}) => { draft[id] = {...draft[id], value} return draft } }
const reducer = (state = {}, {type, payload}: any): any => handlers[type] ? produce<any, any>(handlers[type])(state, payload) : state}modified:__tests__/base.js+1 added-1 removed
722 unmodified lines723 if (useProxies)724 it("should not allow changing prototype", () => {725 produce({}, draft => {726 expect(() => Object.setPrototypeOf(draft, Array)).toThrow(727- /try this/727+ /does not support `setPrototype/728 )729 })730 })731 205 unmodified linesmodified:src/common.js+13 added-3 removed
52 unmodified lines53 }54 return value55 }56 57+const assign =58+ Object.assign ||59+ function assign(target, value) {60+ for (let key in value) {61+ if (has(value, key)) {62+ target[key] = value[key]63+ }64+ }65+ return target66+ }67+68 export function shallowCopy(value) {69 if (Array.isArray(value)) return value.slice()59- if (value.__proto__ === undefined)60- return Object.assign(Object.create(null), value)61- return Object.assign({}, value)70+ const target = value.__proto__ === undefined ? Object.create(null) : {}71+ return assign(target, value)72 }73 74 export function each(value, cb) {75 if (Array.isArray(value)) {69 unmodified linesmodified:src/es5.js+1 added-1 removed
102 unmodified lines103 JSON.stringify(state.copy || state.base)104 )105 }106 107-// this sounds very expensive, but actually it is not that extensive in practice107+// this sounds very expensive, but actually it is not that expensive in practice108 // as it will only visit proxies, and only do key-based change detection for objects for109 // which it is not already know that they are changed (that is, only object for which no known key was changed)110 function markChanges() {111 // intentionally we process the proxies in reverse order;105 unmodified linesmodified:src/immer.d.ts+11 added-11 removed
11 unmodified lines1213141516161718192021222223242526272728293031323233343536373738394041424344444546474849505151525354555556575859596061626363646566676869697071727310 unmodified lines11 unmodified lines * @returns The next state: a new state, or the current state if nothing was modified */export default function<S = any>( currentState: S, recipe: (this: S, draftState: S) => void recipe: (this: S, draftState: S) => void | S): S
// curried invocations with default initial state// 0 additional argumentsexport default function<S = any>( recipe: (this: S, draftState: S) => void, recipe: (this: S, draftState: S) => void | S, initialState: S): (currentState: S | undefined) => S// 1 additional argument of type Aexport default function<S = any, A = any>( recipe: (this: S, draftState: S, a: A) => void, recipe: (this: S, draftState: S, a: A) => void | S, initialState: S): (currentState: S | undefined, a: A) => S// 2 additional arguments of types A and Bexport default function<S = any, A = any, B = any>( recipe: (this: S, draftState: S, a: A, b: B) => void, recipe: (this: S, draftState: S, a: A, b: B) => void | S, initialState: S): (currentState: S | undefined, a: A, b: B) => S// 3 additional arguments of types A, B and Cexport default function<S = any, A = any, B = any, C = any>( recipe: (this: S, draftState: S, a: A, b: B, c: C) => void, recipe: (this: S, draftState: S, a: A, b: B, c: C) => void | S, initialState: S): (currentState: S | undefined, a: A, b: B, c: C) => S// any number of additional arguments, but with loss of type safety// this may be alleviated if "variadic kinds" makes it into Typescript:// https://github.com/Microsoft/TypeScript/issues/5453export default function<S = any>( recipe: (this: S, draftState: S, ...extraArgs: any[]) => void, recipe: (this: S, draftState: S, ...extraArgs: any[]) => void | S, initialState: S): (currentState: S | undefined, ...extraArgs: any[]) => S
// curried invocations without default initial state// 0 additional argumentsexport default function<S = any>( recipe: (this: S, draftState: S) => void recipe: (this: S, draftState: S) => void | S): (currentState: S) => S// 1 additional argument of type Aexport default function<S = any, A = any>( recipe: (this: S, draftState: S, a: A) => void recipe: (this: S, draftState: S, a: A) => void | S): (currentState: S, a: A) => S// 2 additional arguments of types A and Bexport default function<S = any, A = any, B = any>( recipe: (this: S, draftState: S, a: A, b: B) => void recipe: (this: S, draftState: S, a: A, b: B) => void | S): (currentState: S, a: A, b: B) => S// 3 additional arguments of types A, B and Cexport default function<S = any, A = any, B = any, C = any>( recipe: (this: S, draftState: S, a: A, b: B, c: C) => void recipe: (this: S, draftState: S, a: A, b: B, c: C) => void | S): (currentState: S, a: A, b: B, c: C) => S// any number of additional arguments, but with loss of type safety// this may be alleviated if "variadic kinds" makes it into Typescript:// https://github.com/Microsoft/TypeScript/issues/5453export default function<S = any>( recipe: (this: S, draftState: S, ...extraArgs: any[]) => void recipe: (this: S, draftState: S, ...extraArgs: any[]) => void | S): (currentState: S, ...extraArgs: any[]) => S/** * Automatically freezes any state trees generated by immer. * This protects against accidental modifications of the state tree outside of an immer function.10 unmodified linesmodified:src/immer.js.flow+11 added-11 removed
13 unmodified lines14 * @returns The next state: a new state, or the current state if nothing was modified15 */16 declare export default function produce<S>(17 currentState: S,18- recipe: (draftState: S) => void18+ recipe: (draftState: S) => S | void19 ): S20 // curried invocations with inital state21 declare export default function produce<S, A, B, C>(22- recipe: (draftState: S, a: A, b: B, c: C) => void,22+ recipe: (draftState: S, a: A, b: B, c: C) => S | void,23 initialState: S24 ): (currentState: S | void, a: A, b: B, c: C) => S25 declare export default function produce<S, A, B>(26- recipe: (draftState: S, a: A, b: B) => void,26+ recipe: (draftState: S, a: A, b: B) => S | void,27 initialState: S28 ): (currentState: S | void, a: A, b: B) => S29 declare export default function produce<S, A>(30- recipe: (draftState: S, a: A) => void,30+ recipe: (draftState: S, a: A) => S | void,31 initialState: S32 ): (currentState: S | void, a: A) => S33 declare export default function produce<S>(34- recipe: (draftState: S) => void,34+ recipe: (draftState: S) => S | void,35 initialState: S36 ): (currentState: S | void) => S37 declare export default function produce<S>(38- recipe: (draftState: S, ...extraArgs: any[]) => void,38+ recipe: (draftState: S, ...extraArgs: any[]) => S | void,39 initialState: S40 ): (currentState: S | void, ...extraArgs: any[]) => S41 // curried invocations without inital state42 declare export default function produce<S, A, B, C>(43- recipe: (draftState: S, a: A, b: B, c: C) => void43+ recipe: (draftState: S, a: A, b: B, c: C) => S | void44 ): (currentState: S, a: A, b: B, c: C) => S45 declare export default function produce<S, A, B>(46- recipe: (draftState: S, a: A, b: B) => void46+ recipe: (draftState: S, a: A, b: B) => S | void47 ): (currentState: S, a: A, b: B) => S48 declare export default function produce<S, A>(49- recipe: (draftState: S, a: A) => void49+ recipe: (draftState: S, a: A) => S | void50 ): (currentState: S, a: A) => S51 declare export default function produce<S>(52- recipe: (draftState: S) => void52+ recipe: (draftState: S) => S | void53 ): (currentState: S) => S54 declare export default function produce<S>(55- recipe: (draftState: S, ...extraArgs: any[]) => void55+ recipe: (draftState: S, ...extraArgs: any[]) => S | void56 ): (currentState: S, ...extraArgs: any[]) => S57 /**58 * Automatically freezes any state trees generated by immer.59 * This protects against accidental modifications of the state tree outside of an immer function.10 unmodified linesmodified:src/proxy.js+2 added-2 removed
26 unmodified lines27 deleteProperty,28 getOwnPropertyDescriptor,29 defineProperty,30 setPrototypeOf() {31- throw new Error("Don't even try this...")31+ throw new Error("Immer does not support `setPrototypeOf()`.")32 }33 }34 35 const arrayTraps = {}67 unmodified lines103 }104 105 function defineProperty() {106 throw new Error(107- "Immer does currently not support defining properties on draft objects"107+ "Immer does not support defining properties on draft objects."108 )109 }110 111 function markChanged(state) {55 unmodified linesmodified:changelog.md+4 added
1 # Changelog2 3+### 1.2.14+5+* Improved TypeScript and Flow typings to support return a new state from a producer. Trough [#131](https://github.com/mweststrate/immer/pull/131) by [dmorosinotto](https://github.com/mweststrate/immer/issues?q=is%3Apr+author%3Admorosinotto) resp [#127](https://github.com/mweststrate/immer/pull/127) by [bugzpodder](https://github.com/mweststrate/immer/pull/127)6+7 ### 1.28 9 * It is now possible to pass an _initial state_ to a _curried producer_. This makes it simpler to write Redux reducers that have a default initial state. See [#121](https://github.com/mweststrate/immer/pull/121) by (@pkerschbaum)[https://github.com/pkerschbaum]. Implements [#111](https://github.com/mweststrate/immer/issues/111).10 * Improved TypeScript & Flow typings. See [#109]](https://github.com/mweststrate/immer/pull/109) by [ogwh](https://github.com/ogwh).141 unmodified linesmodified:package.json+2 added-2 removed
1 {2 "name": "immer",3- "version": "1.2.0",3+ "version": "1.2.1",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/immer.js",6 "umd:main": "dist/immer.umd.js",7 "module": "dist/immer.module.js",42 unmodified lines50 "coveralls": "^3.0.0",51 "cpx": "^1.5.0",52 "cross-env": "^5.1.3",53 "deep-freeze": "^0.0.1",54- "flow-bin": "^0.65.0",54+ "flow-bin": "^0.68.0",55 "husky": "^0.14.3",56 "immutable": "^3.8.2",57 "jest": "^22.0.4",58 "lint-staged": "^6.1.0",28 unmodified linesmodified:readme.md+115 added-136 removed
1 # Immer2 3-[](https://www.npmjs.com/package/immer)4-[](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)5-[](https://travis-ci.org/mweststrate/immer)6-[](https://coveralls.io/github/mweststrate/immer?branch=master)7-[](https://github.com/prettier/prettier)8-[](https://www.paypal.me/michelweststrate)3+[](https://www.npmjs.com/package/immer) [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js) [](https://travis-ci.org/mweststrate/immer) [](https://coveralls.io/github/mweststrate/immer?branch=master) [](https://github.com/prettier/prettier) [](https://www.paypal.me/michelweststrate)4 5 _Create the next immutable state tree by simply modifying the current tree_6 7 ---8 9 * NPM: `npm install immer`10 * Yarn: `yarn add immer`11 * CDN: Exposed global is `immer`17- * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`18- * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`12+ * Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`13+ * JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`14 15 ---16 17 * Egghead lesson covering all of immer (7m): [Simplify creating immutable data trees with Immer](https://egghead.io/lessons/redux-simplify-creating-immutable-data-trees-with-immer)18 * Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)19 25-Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.26-It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.20+Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way. It is based on the [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.21 28-The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_.29-Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state.30-This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.22+The basic idea is that you will apply all your changes to a temporarily _draftState_, which is a proxy of the _currentState_. Once all your mutations are completed, Immer will produce the _nextState_ based on the mutations to the draft state. This means that you can interact with your data by simply modifying it, while keeping all the benefits of immutable data.23 24 25 26 Using Immer is like having a personal assistant; he takes a letter (the current state), and gives you a copy (draft) to jot changes onto. Once you are done, the assistant will take your draft and produce the real immutable, final letter for you (the next state).24 unmodified lines51 }52 ]53 54 const nextState = produce(baseState, draftState => {63- draftState.push({ todo: "Tweet about it" })55+ draftState.push({todo: "Tweet about it"})56 draftState[1].done = true57 })58 ```59 34 unmodified lines94 ```javascript95 // Redux reducer96 // Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js97 const byId = (state, action) => {106- switch (action.type) {107- case RECEIVE_PRODUCTS:108- return {109- ...state,110- ...action.products.reduce((obj, product) => {111- obj[product.id] = product112- return obj113- }, {})114- }115- default:116- return state117- }98+ switch (action.type) {99+ case RECEIVE_PRODUCTS:100+ return {101+ ...state,102+ ...action.products.reduce((obj, product) => {103+ obj[product.id] = product104+ return obj105+ }, {})106+ }107+ default:108+ return state109+ }110 }111 ```112 113 After using Immer, that simply becomes:114 115 ```javascript124-import produce from 'immer'116+import produce from "immer"117 118 const byId = (state, action) =>127- produce(state, draft => {128- switch (action.type) {129- case RECEIVE_PRODUCTS:130- action.products.forEach(product => {131- draft[product.id] = product132- })133- }134- })119+ produce(state, draft => {120+ switch (action.type) {121+ case RECEIVE_PRODUCTS:122+ action.products.forEach(product => {123+ draft[product.id] = product124+ })125+ }126+ })127 ```128 129 Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.130 139-Creating Redux reducer is just a sample application of the Immer package.140-Immer is not just designed to simplify Redux reducers.141-It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).131+Creating Redux reducer is just a sample application of the Immer package. Immer is not just designed to simplify Redux reducers. It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing).132 133 _Note: it might be tempting after using producers for a while, to just place `produce` in your root reducer and then pass the draft to each reducer and work directly over such draft. Don't do that. It kills the point of Redux where each reducer is testable as pure reducer. Immer is best used when applying it to small individual pieces of logic._134 135 ## React.setState example136 147-Deep updates in the state of React components can be greatly simplified as well by using immer.148-Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):137+Deep updates in the state of React components can be greatly simplified as well by using immer. Take for example the following onClick handlers (Try in [codesandbox](https://codesandbox.io/s/m4yp57632j)):138 139 ```javascript140 /**141 * Classic React.setState with a deep merge142 */143 onBirthDayClick1 = () => {155- this.setState((prevState)=>({144+ this.setState(prevState => ({145 user: {146 ...prevState.user,147 age: prevState.user.age + 1148 }2 unmodified lines151 152 /**153 * ...But, since setState accepts functions,154 * we can just create a curried producer and further simplify!166-*/155+ */156 onBirthDayClick2 = () => {157+ this.setState(168- this.setState(produce(draft => {169- draft.user.age += 1170- }))158+ produce(draft => {159+ draft.user.age += 1160+ })161+ )162 }163 ```164 165 ## Currying166 176-Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from.177-The producer function gets passed in the draft, and any further arguments that were passed to the curried function.167+Passing a function as the first argument to `produce` is intended to be used for currying. This means that you get a pre-bound producer that only needs a state to produce the value from. The producer function gets passed in the draft, and any further arguments that were passed to the curried function.168 169 For example:170 171 ```javascript28 unmodified lines200 201 If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:202 203 ```javascript214-import produce from 'immer'204+import produce from "immer"205 206 const byId = produce(217- (draft, action) => {218- switch (action.type) {219- case RECEIVE_PRODUCTS:220- action.products.forEach(product => {221- draft[product.id] = product222- })223- return207+ (draft, action) => {208+ switch (action.type) {209+ case RECEIVE_PRODUCTS:210+ action.products.forEach(product => {211+ draft[product.id] = product212+ })213+ return214+ }215+ },216+ {217+ 1: {id: 1, name: "product-1"}218 }225- },226- {227- 1: { id: 1, name: "product-1" }228- }219 )220 ```221 222 ## Auto freezing223 234- Immer automatically freezes any state trees that are modified using `produce`.235- This protects against accidental modifications of the state tree outside of a producer.236- This comes with a performance impact, so it is recommended to disable this option in production.237- It is by default enabled.238- By default it is turned on during local development, and turned off in production.239- Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.224+Immer automatically freezes any state trees that are modified using `produce`. This protects against accidental modifications of the state tree outside of a producer. This comes with a performance impact, so it is recommended to disable this option in production. It is by default enabled. By default it is turned on during local development, and turned off in production. Use `setAutoFreeze(true / false)` to explicitly turn this feature on or off.225 226 ## Returning data from producers227 243-It is not needed to return anything from a producer, as Immer will return the (finalized) version of the `draft` anyway.244-However, it is allowed to just `return draft`.228+It 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`.229 246-It is also allowed to return arbitrarily other data from the producer function. But _only_ if you didn't modify the draft.247-This can be useful to produce an entirely new state. Some examples:230+It 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:231 232 ```javascript233 const userReducer = produce((draft, action) => {251- switch (action.type) {252- case "renameUser":253- // OK: we modify the current state254- draft.users[action.payload.id].name = action.payload.name255- return draft // same as just 'return'256- case "loadUsers":257- // OK: we return an entirely new state258- return action.payload259- case "adduser-1":260- // NOT OK: This doesn't do change the draft nor return a new state!261- // It doesn't modify the draft (it just redeclares it)262- // In fact, this just doesn't do anything at all263- draft = { users: [...draft.users, action.payload]}264- return265- case "adduser-2":266- // NOT OK: modifying draft *and* returning a new state267- draft.userCount += 1268- return { users: [...draft.users, action.payload] }269- case "adduser-3":270- // OK: returning a new state. But, unnecessary complex and expensive271- return {272- userCount: draft.userCount + 1,273- users: [...draft.users, action.payload]274- }275- case "adduser-4":276- // OK: the immer way277- draft.userCount += 1278- draft.push(action.payload)279- return280- }234+ switch (action.type) {235+ case "renameUser":236+ // OK: we modify the current state237+ draft.users[action.payload.id].name = action.payload.name238+ return draft // same as just 'return'239+ case "loadUsers":240+ // OK: we return an entirely new state241+ return action.payload242+ case "adduser-1":243+ // NOT OK: This doesn't do change the draft nor return a new state!244+ // It doesn't modify the draft (it just redeclares it)245+ // In fact, this just doesn't do anything at all246+ draft = {users: [...draft.users, action.payload]}247+ return248+ case "adduser-2":249+ // NOT OK: modifying draft *and* returning a new state250+ draft.userCount += 1251+ return {users: [...draft.users, action.payload]}252+ case "adduser-3":253+ // OK: returning a new state. But, unnecessary complex and expensive254+ return {255+ userCount: draft.userCount + 1,256+ users: [...draft.users, action.payload]257+ }258+ case "adduser-4":259+ // OK: the immer way260+ draft.userCount += 1261+ draft.users.push(action.payload)262+ return263+ }264 })265 ```266 267 ## Using `this`2 unmodified lines270 271 This means that the following constructions are also valid:272 273 ```javascript291-const base = { counter: 0 }274+const base = {counter: 0}275 276 const next = produce(base, function() {294- this.counter++277+ this.counter++278 })279 console.log(next.counter) // 1280 281 // OR282 const increment = produce(function() {300- this.counter++283+ this.counter++284 })285 console.log(increment(base).counter) // 1286 ```287 2 unmodified lines290 The Immer package ships with type definitions inside the package, which should be picked up by TypeScript and Flow out of the box and without further configuration.291 292 ## Immer on older JavaScript environments?293 311-By default `produce` tries to use proxies for optimal performance.312-However, on older JavaScript engines `Proxy` is not available.313-For example, when running Microsoft Internet Explorer or React Native on Android.314-In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.294+By default `produce` tries to use proxies for optimal performance. However, on older JavaScript engines `Proxy` is not available. For example, when running Microsoft Internet Explorer or React Native on Android. In such cases Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.295 296 ## Pitfalls297 298 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).299 1. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.320-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.321-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.322-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`323-5. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.300+1. 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.301+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.302+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`303+1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.304 305 ## Cool things built with immer306 307 * [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_308 * [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_309 * [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_310 * [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux developement quicker and easier_311+* [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_312 313 ## How does Immer work?314 315 Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).2 unmodified lines318 319 _For those who have to go back to thinking in object updates :-)_320 321 ```javascript341-import produce from "immer";322+import produce from "immer"323 324 // object mutations325 const todosObj = {345- id1: { done: false, body: "Take out the trash" },346- id2: { done: false, body: "Check Email" }347-};326+ id1: {done: false, body: "Take out the trash"},327+ id2: {done: false, body: "Check Email"}328+}329 330 // add331 const addedTodosObj = produce(todosObj, draft => {351- draft["id3"] = { done: false, body: "Buy bananas" };352-});332+ draft["id3"] = {done: false, body: "Buy bananas"}333+})334 335 // delete336 const deletedTodosObj = produce(todosObj, draft => {356- delete draft["id1"];357-});337+ delete draft["id1"]338+})339 340 // update341 const updatedTodosObj = produce(todosObj, draft => {361- draft["id1"].done = true;362-});342+ draft["id1"].done = true343+})344 345 // array mutations346 const todosArray = [366- { id: "id1", done: false, body: "Take out the trash" },367- { id: "id2", done: false, body: "Check Email" }368-];347+ {id: "id1", done: false, body: "Take out the trash"},348+ {id: "id2", done: false, body: "Check Email"}349+]350 351 // add352 const addedTodosArray = produce(todosArray, draft => {372- draft.push({ id: "id3", done: false, body: "Buy bananas" });373-});353+ draft.push({id: "id3", done: false, body: "Buy bananas"})354+})355 356 // delete357 const deletedTodosArray = produce(todosArray, draft => {377- draft.splice(draft.findIndex(todo => todo.id === "id1"), 1);378- // or (slower):379- // return draft.filter(todo => todo.id !== "id1")380-});358+ draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)359+ // or (slower):360+ // return draft.filter(todo => todo.id !== "id1")361+})362 363 // update364 const updatedTodosArray = produce(todosArray, draft => {384- draft[draft.findIndex(todo => todo.id === "id1")].done = true;385-});365+ draft[draft.findIndex(todo => todo.id === "id1")].done = true366+})367 ```368 369 ## Performance370 390-Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer.391-This test takes 100.000 todo items, and updates 10.000 of them.392-_Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.371+Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 100.000 todo items, and updates 10.000 of them. _Freeze_ indicates that the state tree has been frozen after producing it. This is a _development_ best practice, as it prevents developers from accidentally modifying the state tree.372 394-These tests were executed on Node 8.4.0.395-Use `yarn test:perf` to reproduce them locally.373+These tests were executed on Node 8.4.0. Use `yarn test:perf` to reproduce them locally.374 375 376 377 Some observations:378+379 * From `immer` perspective, this benchmark is a _worst case_ scenario, because the root collection it has to proxy is really large relatively to the rest of the data set.380 * The _mutate_, and _deepclone, mutate_ benchmarks establish a baseline on how expensive changing the data is, without immutability (or structural sharing in the deep clone case).381 * The _reducer_ and _naive reducer_ are implemented in typical Redux style reducers. The "smart" implementation slices the collection first, and then maps and freezes only the relevant todos. The "naive" implementation just maps over and processes the entire collection.382 * Immer with proxies is roughly speaking twice as slow as a hand written reducer. This is in practice negligible.43 unmodified linesmodified:yarn.lock+3 added-3 removed
1563 unmodified lines1564 resolved "https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7"1565 dependencies:1566 locate-path "^2.0.0"1567 1568-flow-bin@^0.65.0:1569- version "0.65.0"1570- resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.65.0.tgz#64ffeca27211c786e2d68508c65686ba1b8a2169"1568+flow-bin@^0.68.0:1569+ version "0.68.0"1570+ resolved "https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.68.0.tgz#86c2d14857d306eb2e85e274f2eebf543564f623"1571 1572 for-in@^1.0.1:1573 version "1.0.2"1574 resolved "https://registry.yarnpkg.com/for-in/-/for-in-1.0.2.tgz#81068d295a8142ec0ac726c6e2200c30fb6d5e80"2847 unmodified lines