readme.md
This file
Path
readme.md
160 lines · 5.2 KiB · Markdown
Last changed by
fixed typos in readmeGregory Assasiebefore adoption68f6fb5
History of this fileTake it
Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 1–2why, one step back1# Immer2fixed typos in readmeGregory Assasiebefore adoption68f6fb5
line 3why, one step back3_Your personal assistant for creating your next immutable state_Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 4–6why, one step back45---6fixed typos in readmeGregory Assasiebefore adoption68f6fb5
line 7why, one step back7Immer (German for: always) is a tiny package that allows you to work with immutable state in a more convenient way.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 8–9why, one step back8It is based on [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.9fixed typos in readmeGregory Assasiebefore adoption68f6fb5
line 10why, one step back10The basic idea is that, you will apply all your changes to a _draftState_, which is a proxy of the _currentState_ and 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.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 11why, one step back11Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 12why, one step back12<center>Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
line 13why, one step back13Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 14–15why, one step back1415fixed typos in readmeGregory Assasiebefore adoption68f6fb5
line 16why, one step back16Using 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).Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 17–20why, one step back17</center>1819## API20Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 21–22why, one step back21The immer package exposes a single function:22Doc improvementsMichel Weststratebefore adoptiona3fcf04
line 23why, one step back23`immer(currentState, fn: (draftState) => void): nextState`Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 24–38why, one step back2425## Example2627```javascript28const baseState = [29 {30 todo: "Learn typescript",31 done: true32 },33 {34 todo: "Try immer",35 done: false36 }37]38Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 39–41why, one step back39const nextState = immer(baseState, draftState => {40 draftState.push({ todo: "Tweet about it" })41 draftState[1].done = trueFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 42–44why, one step back42})43```44fixed typos in readmeGregory Assasiebefore adoption68f6fb5
line 45why, one step back45The interesting thing about `immer` is that, the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 46–61why, one step back4647```javascript48// the new item is only added to the next state,49// base state is unmodified50expect(baseState.length).toBe(2)51expect(nextState.length).toBe(3)5253// same for the changed 'done' prop54expect(baseState[1].done).toBe(false)55expect(nextState[1].done).toBe(true)5657// unchanged data is structurally shared58expect(nextState[0]).toBe(baseState[0])59// changed data not (dûh)60expect(nextState[1]).not.toBe(baseState[1])61```Doc improvementsMichel Weststratebefore adoptiona3fcf04
lines 62–68why, one step back6263## Benefits6465* Use the language© to construct create your next state66* Strongly typed, no string based paths etc67* Deep updates are trivial68* Small, dependency free library with minimal api surfaceMerge pull request #9 from benbraou/typosMichel Weststratebefore adoptionae0182f
line 69why, one step back69* No accidental mutations of current state, but intentional mutations of a draft stateFixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 70–75why, one step back7071## Reducer Example7273A lot of words; here is a simple example of what difference that could make in practice.74The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)75fixed typos in readmeGregory Assasiebefore adoption68f6fb5
line 76why, one step back76_Note, this is just a sample application of the `immer` package. Immer is designed to just 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)_Disclaimer: not just reduxMichel Weststratebefore adoption0574ae0
line 77why, one step back77Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 78–123why, one step back78```javascript79const todo = (state, action) => {80 switch (action.type) {81 case 'ADD_TODO':82 return {83 id: action.id,84 text: action.text,85 completed: false86 }87 case 'TOGGLE_TODO':88 if (state.id !== action.id) {89 return state90 }9192 return {93 ...state,94 completed: !state.completed95 }96 default:97 return state98 }99}100101const todos = (state = [], action) => {102 switch (action.type) {103 case 'ADD_TODO':104 return [105 ...state,106 todo(undefined, action)107 ]108 case 'TOGGLE_TODO':109 return state.map(t =>110 todo(t, action)111 )112 default:113 return state114 }115}116```117118After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):119120```javascript121import immer from 'immer'122123const todos = (state = [], action) =>readme improvementsMichel Weststratebefore adoptionc674cad
lines 124–125why, one step back124 // immer produces nextState from draftState and returns it125 immer(state, draftState => {Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 126–127why, one step back126 switch (action.type) {127 case 'ADD_TODO':readme improvementsMichel Weststratebefore adoptionc674cad
line 128why, one step back128 draftState.push({Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 129–134why, one step back129 id: action.id,130 text: action.text,131 completed: false132 })133 return134 case 'TOGGLE_TODO':readme improvementsMichel Weststratebefore adoptionc674cad
line 135why, one step back135 const todo = draftState.find(todo => todo.id === action.id)Fixed bug, wrote readmeMichel Weststratebefore adoption1b8a694
lines 136–151why, one step back136 todo.completed = !todo.completed137 return138 }139 })140```141142Creating middleware or reducer wrapper that applies `immer` automatically is left as exercise to the reader :-).143144## Limitations145146* This package requires Proxies, so Safari > 10, no Internet Explorer147* Currently only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)148* Currently only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)149150## Pitfalls:151fixed typos in readmeGregory Assasiebefore adoption68f6fb5
lines 152–153why, one step back152* Make sure to modify the state you get passed in the callback function, not the original base state that was passed as first argument to `immer`!153* Since immer uses proxies, reading huge amounts of data from state comes with an overhead. If this ever becomes an issue (measure before optimize!), do the current state analysis before entering the `immer` block or read from the `currentState` rather than the `draftState`updated changelogMichel Weststratebefore adoptione4ca0d6
lines 154–160why, one step back154155## Changelog156157### 0.0.4 (31-12-2017)158159* Added typescript typings [#11](https://github.com/mweststrate/immer/pull/11) by [@benbraou](https://github.com/benbraou)160* Fixed bug when setting properties to `undefined`. Fixes [#12](https://github.com/mweststrate/immer/issues/12) through [#13](https://github.com/mweststrate/immer/pull/13) by [@benbraou](https://github.com/benbraou)