Gave the readme a sane order
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 4ec6076 · Browse files · 2 files·+101 added−86 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+101 added−86 removed
- tests:+2 added−1 removed
- other:+99 added−85 removed
Provenance
- Commit
821cc3d- Tree
1147d27- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
4ec6076
2 files changed+101 added−86 removed
modified:__tests__/curry.js+2 added-1 removed
4 unmodified lines5678991011121319 unmodified lines33343536373839404 unmodified linesrunTests("proxy", immerProxy)runTests("es5", immerEs5)
function runTests(name, lib) { describe("auto freeze - " + name, () => { describe("curry - " + name, () => { const produce = lib.default
it("should check arguments", () => { expect(() => produce()).toThrow(/produce expects 1 or 2 arguments/)19 unmodified lines {index: 0}, {index: 1}, {index: 2} ]) expect(state).toEqual([{}, {}, {}]) }) })}modified:readme.md+99 added-85 removed
3 unmodified lines4 [](https://coveralls.io/github/mweststrate/immer?branch=master)5 [](https://github.com/prettier/prettier)6 [](https://mobx.js.org/donate.html)7 8-8 _Create the next immutable state tree by simply modifying the current tree_9 10 ---11 10 unmodified lines22 23 24 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).25 27-A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applicable to plain, native JavaScript data structures (arrays and objects) without further needing any library.26+A mindful reader might notice that this is quite similar to `withMutations` of ImmutableJS. It is indeed, but generalized and applied to plain, native JavaScript data structures (arrays and objects) without further needing any library.27 28 ## Installation29 30 `npm install immer`31 32 ## API33 35-The immer package exposes a single function:34+The immer package exposes a default function that does all the work.35 36 `immer(currentState, fn: (draftState) => void): nextState`37 38+There is also a curried overload that is explained [below](#currying)39+40 ## Example41 42 ```javascript43 import immer from "immer"32 unmodified lines76 // changed data not (dûh)77 expect(nextState[1]).not.toBe(baseState[1])78 ```79 79-## Using immer on older JavaScript environments80-81-By default `immer` tries to use proxies for optimal performance.82-However, on older JavaScript engines `Proxy` is not available.83-For example, Microsoft Internet Explorer or React Native on Android.84-In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:85-86-```javascript87-import immer from "immer/es5"88-```89-80 ## Benefits81 92-* Use the language© to construct create your next state93-* Use JavaScript native arrays and object94-* Automatic immutability; any state tree produced by `immer` will by defualt be deeply frozen95-* Strongly typed, no string based paths etc96-* Deep updates are trivial97-* Small, dependency free library with minimal api surface98-* No accidental mutations of current state, but intentional mutations of a draft state82+* Immutability with normal JavaScript objects and arrays. No new APIs to learn!83+* Strongly typed, no string based paths selectors etc.84+* Structural sharing out of the box85+* Object freezing out of the box86+* Deep updates are a breeze87+* Boilerplate reduction. Less noise, more concise code.88 100-## Auto freezing89+Read further to see all these benefits explained.90 102- Immer automatically freezes any state trees that are modified using `immer.103- This protects against accidental modifications of the state tree outside of an immer function.104- This comes with a performance impact, so it is recommended to disable this option in production.105- It is by default enabled.106-107- Use `setAutoFreeze(true / false)` to turn this feature on or off.108-91 ## Reducer Example92 111-Here is a simple example of the difference that this approach could make in practice.112-The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)93+Here is a simple example of the difference that Immer could make in practice.94 114-_Note, this 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)_95 96 ```javascript97+// Redux reducer98+// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js117-const todo = (state, action) => {99+const byId = (state, action) => {100 switch (action.type) {119- case 'ADD_TODO':101+ case RECEIVE_PRODUCTS:102 return {121- id: action.id,122- text: action.text,123- completed: false124- }125- case 'TOGGLE_TODO':126- if (state.id !== action.id) {127- return state128- }129-130- return {103 ...state,132- completed: !state.completed104+ ...action.products.reduce((obj, product) => {105+ obj[product.id] = product106+ return obj107+ }, {})108 }109 default:110 return state111 }112 }138-139-const todos = (state = [], action) => {140- switch (action.type) {141- case 'ADD_TODO':142- return [143- ...state,144- todo(undefined, action)145- ]146- case 'TOGGLE_TODO':147- return state.map(t =>148- todo(t, action)149- )150- default:151- return state152- }153-}113 ```114 156-After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):115+After using immer, that simply becomes:116 117 ```javascript118 import immer from 'immer'119 161-const todos = (state = [], action) =>162- // immer produces nextState from draftState and returns it163- immer(state, draftState => {120+const byId = (state, action) =>121+ produce(state, draft => {122 switch (action.type) {165- case 'ADD_TODO':166- draftState.push({167- id: action.id,168- text: action.text,169- completed: false123+ case RECEIVE_PRODUCTS:124+ action.products.forEach(product => {125+ draft[product.id] = product126 })171- return172- case 'TOGGLE_TODO':173- const todo = draftState.find(todo => todo.id === action.id)174- todo.completed = !todo.completed175- return127 }128 })129 ```130 180-Creating middleware or a reducer wrapper that applies `immer` automatically is left as exercise for the reader :-).131+Note that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.132 182----133+_Note, creating Redux reducer is just a sample application of the `immer` package.134+Immer is not just designed to simplify Redux reducers.135+It can be used in any context where you have an immutable data tree that you want to clone and modify (with structural sharing)_136 137+## Currying138+139+`produce` can be called with one or two arguments.140+The one argument version is intended to be used as currying. This means that you get a pre-pound producer, that only needs a state to produce the value from.141+The producer function get's passed in the draft, and any further arguments that were passed to the curried function.142+143+For example:144+145+```javascript146+// mapper will be of signature (state, index) => state147+const mapper = produce((draft, index) => {148+ draft.index = index149+})150+151+// example usage152+console.dir([{}, {}, {}].map(mapper))153+//[{index: 0}, {index: 1}, {index: 2}])154+```155+156+This mechanism can also nicely be leveraged to further simplify our example reducer:157+158+```javascript159+160+const byId = produce((draft, action) => {161+ switch (action.type) {162+ case RECEIVE_PRODUCTS:163+ action.products.forEach(product => {164+ draft[product.id] = product165+ })166+ }167+})168+```169+170+Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).171+One think to keep in mind; you cannot use this construction to initialize an uninitialized state. E.g. `draft = {}` doesn't do anything useful.172+173+174+## Auto freezing175+176+ Immer automatically freezes any state trees that are modified using `produce`.177+ This protects against accidental modifications of the state tree outside of an immer function.178+ This comes with a performance impact, so it is recommended to disable this option in production.179+ It is by default enabled.180+ Use `setAutoFreeze(true / false)` to turn this feature on or off.181+182+## Using immer on older JavaScript environments183+184+By default `immer` tries to use proxies for optimal performance.185+However, on older JavaScript engines `Proxy` is not available.186+For example, Microsoft Internet Explorer or React Native on Android.187+In these cases, import the ES5 compatibile implementation first, which is a bit slower (see below) but semantically equivalent:188+189+```javascript190+import immer from "immer/es5"191+```192+193+## More reducer examples194+195 Here are some typical reducer examples, take from the Redux [Immutable Update Patterns](https://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) page, and their immer counter part.196 These examples are semantically equivalent and produce the exact same state.197 198 ```javascript53 unmodified lines252 })253 }254 ```255 245-## Limitations256+## Pitfalls257 247-* Currently, only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)248-* Currently, only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)249-250-## Pitfalls:251-258+* Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.259 * 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, it will be that very same object in both the base state as the next state. In such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.253-* Make sure to modify the draft state you get passed in in the callback function, not the original current state that was passed as the first argument to `immer`!254-* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`260+* 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`261 * Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.262 263+## How does immer work?264+265+Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/9d73d8f71cb3).266+267 ## Performance268 269 Here is a [simple benchmark](__tests__/performance.js) on the performance of `immer`.270 This test takes 100.000 todo items, and updates 10.000 of them.14 unmodified lines285 286 ## Credits287 288 Special thanks goes to @Mendix, which supports it's employees to experiment completely freely two full days a month, which formed the kick-start for this project.289+290+## Donations291+292+A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)