Documented patches
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 4eb6bce · Browse files · 4 files·+129 added−2 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+129 added−2 removed
- tests:+49 added−1 removed
- other:+80 added−1 removed
Provenance
- Commit
d60eea0- Tree
2e7cc66- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
4eb6bce
4 files changed+129 added−2 removed
modified:__tests__/readme.js+49 added-1 removed
122345640 unmodified lines4748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899"use strict"import produce from "../src/immer"import produce, {applyPatches} from "../src/immer"
describe("readme example", () => { it("works", () => { const baseState = [40 unmodified lines this.counter++ }) expect(increment(base).counter).toBe(1) })
it("patches", () => { let state = { name: "Micheal", age: 32 }
// Let's assume the user is in a wizard, and we don't know whether // his changes should be updated let fork = state // all the changes the user made in the wizard let changes = [] // all the inverse patches let inverseChanges = []
fork = produce( fork, draft => { draft.age = 33 }, // The third argument to produce is a callback to which the patches will be fed (patches, inversePatches) => { changes.push(...patches) inverseChanges.push(...inversePatches) } )
// In the mean time, our original state is updated as well, as changes come in from the server state = produce(state, draft => { draft.name = "Michel" })
// When the wizard finishes (successfully) we can replay the changes made in the fork onto the *new* state! state = applyPatches(state, changes)
// state now contains the changes from both code paths! expect(state).toEqual({ name: "Michel", age: 33 })
// Even after finishing the wizard, the user might change his mind... state = applyPatches(state, inverseChanges) expect(state).toEqual({ name: "Michel", age: 32 }) })})modified:changelog.md+4 added
1 # Changelog2 3+### 1.5.04+5+* Added support for patches, through [#168](https://github.com/mweststrate/immer/pull/168). See the [patches](https://github.com/mweststrate/immer#patches) section for details6+7 ### 1.4.08 9 * Improved TypeScript typings; if the base state is declared as `readonly`, the `draft` object will be upcasted to a writeable version. Fixes [#97](https://github.com/mweststrate/immer/issues/97) through [#161](https://github.com/mweststrate/immer/pull/161) by [@knpwrs](https://github.com/knpwrs)10 * It is now possible to use both `import produce from "immer"` and `import {produce} from "immer"`. Implements [#136](https://github.com/mweststrate/immer/issues/136)161 unmodified linesmodified:package.json+1 added-1 removed
9 unmodified lines1011121314141516171886 unmodified lines9 unmodified lines "types": "./dist/immer.d.ts", "scripts": { "watch": "jest --watch", "test": "jest", "test:perf": "NODE_ENV=production yarn-or-npm build && cd __preformance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js", "test:perf": "NODE_ENV=production yarn-or-npm build && cd __performance_tests__ && babel-node add-data.js && babel-node todo.js && babel-node incremental.js", "test:flow": "yarn-or-npm flow check", "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js && rm -rf ./coverage", "build": "rimraf dist/ && cross-env NODE_ENV=production rollup -c && cpx \"src/immer.{d.ts,js.flow}\" dist", "prettier": "prettier \"*/**/*.js\" --ignore-path ./.prettierignore --write",86 unmodified linesmodified:readme.md+75 added
218 unmodified lines219 }220 )221 ```222 223+## Patches224+225+During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer.226+This is a very powerful tool if you want to fork your state temporarily, and replay the changes to the original.227+To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used228+to record the incremental updates and (inverse) apply them:229+230+```javascript231+import produce, {applyPatches} from "immer"232+233+let state = {234+ name: "Micheal",235+ age: 32236+}237+238+// Let's assume the user is in a wizard, and we don't know whether239+// his changes should be end up in the base state ultimately or not...240+let fork = state241+// all the changes the user made in the wizard242+let changes = []243+// the inverse of all the changes made in the wizard244+let inverseChanges = []245+246+fork = produce(247+ fork,248+ draft => {249+ draft.age = 33250+ },251+ // The third argument to produce is a callback to which the patches will be fed252+ (patches, inversePatches) => {253+ changes.push(...patches)254+ inverseChanges.push(...inversePatches)255+ }256+)257+258+// In the mean time, our original state is replaced, as, for example,259+// some changes were received from the server260+state = produce(state, draft => {261+ draft.name = "Michel"262+})263+264+// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!265+state = applyPatches(state, changes)266+267+// state now contains the changes from both code paths!268+expect(state).toEqual({269+ name: "Michel", // changed by the server270+ age: 33 // changed by the wizard271+})272+273+// Finally, even after finishing the wizard, the user might change his mind and undo his changes...274+state = applyPatches(state, inverseChanges)275+expect(state).toEqual({276+ name: "Michel", // Not reverted277+ age: 32 // Reverted278+})279+```280+281+The generated patches are similar (but not the same) to the [RFC-6902 JSON patch standard](http://tools.ietf.org/html/rfc6902), except that the `path` property is an array, rather than a string.282+This makes processing patches easier. If you want to normalize to the official specification, `patch.path = patch.path.join("/")` should do the trick. Anyway, this is what a bunch of patches and their inverse could look like:283+284+```json285+[286+ { "op": "replace", "path": ["profile"], "value": { "name": "Veria", age: 5 }},287+ { "op": "remove", "path": ["tags", 3] }288+]289+```290+291+```json292+[293+ { "op": "replace", "path": ["profile"], "value": { "name": "Noa", age: 6 }},294+ { "op": "add", "path": ["tags", 3], "value": "kiddo"},295+]296+```297+298 ## Auto freezing299 300 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.301 244 unmodified lines