Skip to content
Myr

Fixed bug, wrote readme

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 2b2d0cb · Browse files · 4 files+236 added−15 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+236 added−15 removed

  • tests:+90 added−11 removed
  • other:+146 added−4 removed

4 files+236 added−15 removed

modified:__tests__/base.js+90 added-11 removed
modified:immer.js+11 added-2 removed
1// @ts-check23const isProxySymbol = Symbol("immer-proxy")45/**6 * Immer takes a state, and runs a function agains it.7 * That function can freely mutate the state, as it will create copies-on-write.8 * This means that the original state will stay unchanged, and once the function finishes, the modified state is returned
10 unmodified lines
19 const copies = new Map()2021 const objectTraps = {22 get(target, prop) {23 if (prop === isProxySymbol) return target24 return createProxy(getCurrentSource(target)[prop])25 },26 has(target, prop) {27 return prop in getCurrentSource(target)
5 unmodified lines
33 const current = createProxy(getCurrentSource(target)[prop])34 const newValue = createProxy(value)35 if (current !== newValue) {36 const copy = getOrCreateCopy(target)34 copy[prop] = newValue37 copy[prop] = isProxy(newValue) ? newValue[isProxySymbol] : newValue38 }39 return true40 },41 deleteProperty(target, property) {
21 unmodified lines
6364 // creates a proxy for plain objects / arrays65 function createProxy(base) {66 if (isPlainObject(base) || Array.isArray(base)) {67 if (isProxy(base)) return base // avoid double wrapping68 if (proxies.has(base)) return proxies.get(base)69 const proxy = new Proxy(base, objectTraps)70 proxies.set(base, proxy)71 return proxy
9 unmodified lines
81 if (copies.has(base)) return true // a copy was created, so there are changes82 // look deeper83 const keys = Object.keys(base)84 for (let i = 0; i < keys.length; i++) {81 if (hasChanges(base[keys[i]])) return true85 const value = base[keys[i]]86 if ((Array.isArray(value) || isPlainObject(value)) && hasChanges(value)) return true87 }88 return false89 }90
35 unmodified lines
126 const proto = Object.getPrototypeOf(value)127 return proto === Object.prototype || proto === null128}129130function isProxy(value) {131 return !!value[isProxySymbol]132}133134module.exports = immer
modified:package.json+4 added-1 removed
1{2 "name": "immer",3 "version": "0.0.1",3 "version": "0.0.2",4 "description": "Create your next immutable state by mutating the current one",5 "main": "immer.js",6 "scripts": {7 "test": "jest"
12 unmodified lines
20 "bugs": {21 "url": "https://github.com/mweststrate/immer/issues"22 },23 "homepage": "https://github.com/mweststrate/immer#readme",24 "files": [25 "immer.js"26 ],27 "dependencies": {},28 "devDependencies": {29 "@types/jest": "^22.0.0",30 "babel-core": "^6.26.0",
12 unmodified lines
modified:readme.md+131 added-1 removed
1Soon!1# Immer23Immer (German for: always) is a tiny package that allows you work with immutable state in a more convenient way.4It is based on [_copy-on-write_](https://en.wikipedia.org/wiki/Copy-on-write) mechanism.56The basic idea is that you will modify (a proxy of) the current state, and once that is completed, the copy will be finalized and form the next state.7As soon as a piece of the state is modified, it is copied. That is what one typically does by hand (in for example Redux reducers).89_This means that you can interact with your data by using mutations, will keeping all the benefits of immutable data_1011The immer package exposes a single function:1213`immer(currentState, fn: (state) => void): nextState`1415## Example1617```javascript18const baseState = [19 {20 todo: "Learn typescript",21 done: true22 },23 {24 todo: "Try immer",25 done: false26 }27]2829const nextState = immer(baseState, state => {30 state.push({ todo: "Tweet about it" })31 state[1].done = true32})33```3435The interesting thing about `immer` is that `baseState` will be untouched, but that `nextState` will reflect all changes made to `state`.3637```javascript38// the new item is only added to the next state,39// base state is unmodified40expect(baseState.length).toBe(2)41expect(nextState.length).toBe(3)4243// same for the changed 'done' prop44expect(baseState[1].done).toBe(false)45expect(nextState[1].done).toBe(true)4647// unchanged data is structurally shared48expect(nextState[0]).toBe(baseState[0])49// changed data not (dûh)50expect(nextState[1]).not.toBe(baseState[1])51```5253## Reducer Example5455A lot of words; here is a simple example of what difference that could make in practice.56The todo reducers from the official Redux [todos-with-undo example](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo)5758```javascript59const todo = (state, action) => {60 switch (action.type) {61 case 'ADD_TODO':62 return {63 id: action.id,64 text: action.text,65 completed: false66 }67 case 'TOGGLE_TODO':68 if (state.id !== action.id) {69 return state70 }7172 return {73 ...state,74 completed: !state.completed75 }76 default:77 return state78 }79}8081const todos = (state = [], action) => {82 switch (action.type) {83 case 'ADD_TODO':84 return [85 ...state,86 todo(undefined, action)87 ]88 case 'TOGGLE_TODO':89 return state.map(t =>90 todo(t, action)91 )92 default:93 return state94 }95}96```9798After using immer, that simply [becomes](https://codesandbox.io/s/xl11qpo9mp):99100```javascript101import immer from 'immer'102103const todos = (state = [], action) =>104 immer(state, state => {105 switch (action.type) {106 case 'ADD_TODO':107 state.push({108 id: action.id,109 text: action.text,110 completed: false111 })112 return113 case 'TOGGLE_TODO':114 const todo = state.find(todo => todo.id === action.id)115 todo.completed = !todo.completed116 return117 }118 })119```120121Creating middleware or reducer wrapper that applies `immer` automatically is left as exercise to the reader :-).122123## Limitations124125* This package requires Proxies, so Safari > 10, no Internet Explorer126* Currently only tree shaped states are supported. Cycles could potentially be supported as well (PR's welcome)127* Currently only supports plain objects and arrays. Non-plain data structures (like `Map`, `Set`) not (yet). (PR's welcome)128129## Pitfalls:130131* Make sure to modify the state you get passed in in the callback function, not the original base state that was passed as first argument to `immer`!