WIP
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 b1e2217 · Browse files · 8 files·+820 added−910 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+820 added−910 removed
- other:+820 added−910 removed
Provenance
- Commit
79ec197- Tree
a915d17- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
b1e2217
8 files changed+820 added−910 removed
modified:docs/doc1.md+807 added-11 removed
2 unmodified lines3 title: Latin-ish4 sidebar_label: Example Page5 ---6 7-Check the [documentation](https://docusaurus.io) for how to use Docusaurus.7+- NPM: `npm install immer`8+- Yarn: `yarn add immer`9+- CDN: Exposed global is `immer`10+ - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`11+ - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`12 9-## Lorem13+---14 11-Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque elementum dignissim ultricies. Fusce rhoncus ipsum tempor eros aliquam consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus elementum massa eget nulla aliquet sagittis. Proin odio tortor, vulputate ut odio in, ultrices ultricies augue. Cras ornare ultrices lorem malesuada iaculis. Etiam sit amet libero tempor, pulvinar mauris sed, sollicitudin sapien.15+- 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)16+- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)17 13-## Mauris In Code18+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.19 20+The basic idea is that you will apply all your changes to a temporary _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.21+22+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+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+## External resources29+30+- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)31+- Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)32+- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)33+- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)34+- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate35+- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)36+37+## API38+39+The Immer package exposes a default function that does all the work.40+41+`produce(currentState, producer: (draftState) => void): nextState`42+43+There is also a curried overload that is explained [below](#currying).44+45+## Example46+47+```javascript48+import produce from "immer"49+50+const baseState = [51+ {52+ todo: "Learn typescript",53+ done: true54+ },55+ {56+ todo: "Try immer",57+ done: false58+ }59+]60+61+const nextState = produce(baseState, draftState => {62+ draftState.push({todo: "Tweet about it"})63+ draftState[1].done = true64+})65 ```16-Mauris vestibulum ullamcorper nibh, ut semper purus pulvinar ut. Donec volutpat orci sit amet mauris malesuada, non pulvinar augue aliquam. Vestibulum ultricies at urna ut suscipit. Morbi iaculis, erat at imperdiet semper, ipsum nulla sodales erat, eget tincidunt justo dui quis justo. Pellentesque dictum bibendum diam at aliquet. Sed pulvinar, dolor quis finibus ornare, eros odio facilisis erat, eu rhoncus nunc dui sed ex. Nunc gravida dui massa, sed ornare arcu tincidunt sit amet. Maecenas efficitur sapien neque, a laoreet libero feugiat ut.66+67+The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.68+69+```javascript70+// the new item is only added to the next state,71+// base state is unmodified72+expect(baseState.length).toBe(2)73+expect(nextState.length).toBe(3)74+75+// same for the changed 'done' prop76+expect(baseState[1].done).toBe(false)77+expect(nextState[1].done).toBe(true)78+79+// unchanged data is structurally shared80+expect(nextState[0]).toBe(baseState[0])81+// changed data not (dûh)82+expect(nextState[1]).not.toBe(baseState[1])83 ```84 19-## Nulla85+## Benefits86 21-Nulla facilisi. Maecenas sodales nec purus eget posuere. Sed sapien quam, pretium a risus in, porttitor dapibus erat. Sed sit amet fringilla ipsum, eget iaculis augue. Integer sollicitudin tortor quis ultricies aliquam. Suspendisse fringilla nunc in tellus cursus, at placerat tellus scelerisque. Sed tempus elit a sollicitudin rhoncus. Nulla facilisi. Morbi nec dolor dolor. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Cras et aliquet lectus. Pellentesque sit amet eros nisi. Quisque ac sapien in sapien congue accumsan. Nullam in posuere ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin lacinia leo a nibh fringilla pharetra.87+- Immutability with normal JavaScript objects and arrays. No new APIs to learn!88+- Strongly typed, no string based paths selectors etc.89+- Structural sharing out of the box90+- Object freezing out of the box91+- Deep updates are a breeze92+- Boilerplate reduction. Less noise, more concise code.93+- Small [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)94 23-## Orci95+Read further to see all these benefits explained.96 25-Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin venenatis lectus dui, vel ultrices ante bibendum hendrerit. Aenean egestas feugiat dui id hendrerit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Curabitur in tellus laoreet, eleifend nunc id, viverra leo. Proin vulputate non dolor vel vulputate. Curabitur pretium lobortis felis, sit amet finibus lorem suscipit ut. Sed non mollis risus. Duis sagittis, mi in euismod tincidunt, nunc mauris vestibulum urna, at euismod est elit quis erat. Phasellus accumsan vitae neque eu placerat. In elementum arcu nec tellus imperdiet, eget maximus nulla sodales. Curabitur eu sapien eget nisl sodales fermentum.97+## Reducer Example98 27-## Phasellus99+Here is a simple example of the difference that Immer could make in practice.100 29-Phasellus pulvinar ex id commodo imperdiet. Praesent odio nibh, sollicitudin sit amet faucibus id, placerat at metus. Donec vitae eros vitae tortor hendrerit finibus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Quisque vitae purus dolor. Duis suscipit ac nulla et finibus. Phasellus ac sem sed dui dictum gravida. Phasellus eleifend vestibulum facilisis. Integer pharetra nec enim vitae mattis. Duis auctor, lectus quis condimentum bibendum, nunc dolor aliquam massa, id bibendum orci velit quis magna. Ut volutpat nulla nunc, sed interdum magna condimentum non. Sed urna metus, scelerisque vitae consectetur a, feugiat quis magna. Donec dignissim ornare nisl, eget tempor risus malesuada quis.101+```javascript102+// Redux reducer103+// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js104+const byId = (state, action) => {105+ switch (action.type) {106+ case RECEIVE_PRODUCTS:107+ return {108+ ...state,109+ ...action.products.reduce((obj, product) => {110+ obj[product.id] = product111+ return obj112+ }, {})113+ }114+ default:115+ return state116+ }117+}118+```119+120+After using Immer, that simply becomes:121+122+```javascript123+import produce from "immer"124+125+const byId = (state, action) =>126+ produce(state, draft => {127+ switch (action.type) {128+ case RECEIVE_PRODUCTS:129+ action.products.forEach(product => {130+ draft[product.id] = product131+ })132+ }133+ })134+```135+136+Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.137+138+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).139+140+_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._141+142+## React.setState example143+144+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)):145+146+```javascript147+/**148+ * Classic React.setState with a deep merge149+ */150+onBirthDayClick1 = () => {151+ this.setState(prevState => ({152+ user: {153+ ...prevState.user,154+ age: prevState.user.age + 1155+ }156+ }))157+}158+159+/**160+ * ...But, since setState accepts functions,161+ * we can just create a curried producer and further simplify!162+ */163+onBirthDayClick2 = () => {164+ this.setState(165+ produce(draft => {166+ draft.user.age += 1167+ })168+ )169+}170+```171+172+## Currying173+174+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.175+176+For example:177+178+```javascript179+// mapper will be of signature (state, index) => state180+const mapper = produce((draft, index) => {181+ draft.index = index182+})183+184+// example usage185+console.dir([{}, {}, {}].map(mapper))186+//[{index: 0}, {index: 1}, {index: 2}])187+```188+189+This mechanism can also nicely be leveraged to further simplify our example reducer:190+191+```javascript192+import produce from "immer"193+194+const byId = produce((draft, action) => {195+ switch (action.type) {196+ case RECEIVE_PRODUCTS:197+ action.products.forEach(product => {198+ draft[product.id] = product199+ })200+ return201+ }202+})203+```204+205+Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).206+207+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`:208+209+```javascript210+import produce from "immer"211+212+const byId = produce(213+ (draft, action) => {214+ switch (action.type) {215+ case RECEIVE_PRODUCTS:216+ action.products.forEach(product => {217+ draft[product.id] = product218+ })219+ return220+ }221+ },222+ {223+ 1: {id: 1, name: "product-1"}224+ }225+)226+```227+228+##### Fun with currying229+230+A random fun example just for inspiration: a neat trick is to turn `Object.assign` into a producer to create a "spread" function that is smarter than the normal spread operator, as it doesn't produce a new state if the result doesn't actually change ([details & explanation](https://twitter.com/mweststrate/status/1045059430256119809)). Quick example:231+232+```javascript233+import produce from "immer"234+const spread = produce(Object.assign)235+236+const base = {x: 1, y: 1}237+238+console.log({...base, y: 1} === base) // false239+console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced240+console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should241+```242+243+## Patches244+245+During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer. This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.246+247+Patches are useful in few scenarios:248+249+- To exchange incremental updates with other parties, for example over websockets250+- For debugging / traces, to see precisely how state is changed over time251+- As basis for undo/redo or as an approach to replay changes on a slightly different state tree252+253+To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used to record the incremental updates and (inverse) apply them:254+255+```javascript256+import produce, {applyPatches} from "immer"257+258+let state = {259+ name: "Micheal",260+ age: 32261+}262+263+// Let's assume the user is in a wizard, and we don't know whether264+// his changes should end up in the base state ultimately or not...265+let fork = state266+// all the changes the user made in the wizard267+let changes = []268+// the inverse of all the changes made in the wizard269+let inverseChanges = []270+271+fork = produce(272+ fork,273+ draft => {274+ draft.age = 33275+ },276+ // The third argument to produce is a callback to which the patches will be fed277+ (patches, inversePatches) => {278+ changes.push(...patches)279+ inverseChanges.push(...inversePatches)280+ }281+)282+283+// In the meantime, our original state is replaced, as, for example,284+// some changes were received from the server285+state = produce(state, draft => {286+ draft.name = "Michel"287+})288+289+// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!290+state = applyPatches(state, changes)291+292+// state now contains the changes from both code paths!293+expect(state).toEqual({294+ name: "Michel", // changed by the server295+ age: 33 // changed by the wizard296+})297+298+// Finally, even after finishing the wizard, the user might change his mind and undo his changes...299+state = applyPatches(state, inverseChanges)300+expect(state).toEqual({301+ name: "Michel", // Not reverted302+ age: 32 // Reverted303+})304+```305+306+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. 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:307+308+```json309+[310+ {311+ "op": "replace",312+ "path": ["profile"],313+ "value": {"name": "Veria", "age": 5}314+ },315+ {"op": "remove", "path": ["tags", 3]}316+]317+```318+319+```json320+[321+ {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},322+ {"op": "add", "path": ["tags", 3], "value": "kiddo"}323+]324+```325+326+### `produceWithPatches`327+328+Instead of setting up a patch listener, an easier way to obtain the patches is to use `produceWithPatches`, which has the same signature as `produce`, except that it doesn't return just the next state, but a tuple consisting of `[nextState, patches, inversePatches]`. Like `produce`, `produceWithPatches` supports currying as well.329+330+```javascript331+import {produceWithPatches} from "immer"332+333+const [nextState, patches, inversePatches] = produceWithPatches(334+ {335+ age: 33336+ },337+ draft => {338+ draft.age++339+ }340+)341+```342+343+Which produces:344+345+```javascript346+;[347+ {348+ age: 34349+ },350+ [351+ {352+ op: "replace",353+ path: ["age"],354+ value: 34355+ }356+ ],357+ [358+ {359+ op: "replace",360+ path: ["age"],361+ value: 33362+ }363+ ]364+]365+```366+367+For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)368+369+Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.370+371+## Async producers372+373+It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:374+375+```javascript376+import produce from "immer"377+378+const user = {379+ name: "michel",380+ todos: []381+}382+383+const loadedUser = await produce(user, async function(draft) {384+ draft.todos = await (await window.fetch("http://host/" + draft.name)).json()385+})386+```387+388+_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._389+390+## `createDraft` and `finishDraft`391+392+`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:393+394+```javascript395+import {createDraft, finishDraft} from "immer"396+397+const user = {398+ name: "michel",399+ todos: []400+}401+402+const draft = createDraft(user)403+draft.todos = await (await window.fetch("http://host/" + draft.name)).json()404+const loadedUser = finishDraft(draft)405+```406+407+Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.408+409+_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._410+411+## Returning data from producers412+413+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`.414+415+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:416+417+```javascript418+const userReducer = produce((draft, action) => {419+ switch (action.type) {420+ case "renameUser":421+ // OK: we modify the current state422+ draft.users[action.payload.id].name = action.payload.name423+ return draft // same as just 'return'424+ case "loadUsers":425+ // OK: we return an entirely new state426+ return action.payload427+ case "adduser-1":428+ // NOT OK: This doesn't do change the draft nor return a new state!429+ // It doesn't modify the draft (it just redeclares it)430+ // In fact, this just doesn't do anything at all431+ draft = {users: [...draft.users, action.payload]}432+ return433+ case "adduser-2":434+ // NOT OK: modifying draft *and* returning a new state435+ draft.userCount += 1436+ return {users: [...draft.users, action.payload]}437+ case "adduser-3":438+ // OK: returning a new state. But, unnecessary complex and expensive439+ return {440+ userCount: draft.userCount + 1,441+ users: [...draft.users, action.payload]442+ }443+ case "adduser-4":444+ // OK: the immer way445+ draft.userCount += 1446+ draft.users.push(action.payload)447+ return448+ }449+})450+```451+452+_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._453+454+## Producing `undefined` using `nothing`455+456+So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft. There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:457+458+```javascript459+produce({}, draft => {460+ // don't do anything461+})462+```463+464+Versus:465+466+```javascript467+produce({}, draft => {468+ // Try to return undefined from the producer469+ return undefined470+})471+```472+473+The problem is that in JavaScript a function that doesn't return anything also returns `undefined`! So immer cannot differentiate between those different cases. So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.474+475+However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:476+477+```javascript478+import produce, {nothing} from "immer"479+480+const state = {481+ hello: "world"482+}483+484+produce(state, draft => {})485+produce(state, draft => undefined)486+// Both return the original state: { hello: "world"}487+488+produce(state, draft => nothing)489+// Produces a new state, 'undefined'490+```491+492+N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.493+494+## Inline shortcuts using `void`495+496+Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.497+498+In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.499+500+```javascript501+// Single mutation502+produce(draft => void (draft.user.age += 1))503+504+// Multiple mutations505+produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))506+```507+508+Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.509+510+## Extracting the original object from a proxied instance511+512+Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.513+514+```js515+import {original} from "immer"516+517+const baseState = {users: [{name: "Richie"}]}518+const nextState = produce(baseState, draftState => {519+ original(draftState.users) // is === baseState.users520+})521+```522+523+Just want to know if a value is a proxied instance? Use the `isDraft` function!524+525+```js526+import {isDraft} from "immer"527+528+const baseState = {users: [{name: "Bobby"}]}529+const nextState = produce(baseState, draft => {530+ isDraft(draft) // => true531+ isDraft(draft.users) // => true532+ isDraft(draft.users[0]) // => true533+})534+isDraft(nextState) // => false535+```536+537+## Auto freezing538+539+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.540+541+_⚠️ If auto freezing is enabled, recipes are not entirely side-effect free: Any plain object or array that ends up in the produced result, will be frozen, even when these objects were not frozen before the start of the producer! ⚠️_542+543+## Immer on older JavaScript environments?544+545+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 (< v0.59) on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.546+547+## Importing immer548+549+`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommended:550+551+```javascript552+import produce from "immer"553+import {produce} from "immer"554+555+const {produce} = require("immer")556+const produce = require("immer").produce557+const produce = require("immer").default558+559+import unleashTheMagic from "immer"560+import {produce as unleashTheMagic} from "immer"561+```562+563+## Supported object types564+565+Plain objects and arrays are always drafted by Immer.566+567+Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.568+569+```js570+import {immerable} from "immer"571+572+class Foo {573+ [immerable] = true // Option 1574+575+ constructor() {576+ this[immerable] = true // Option 2577+ }578+}579+580+Foo[immerable] = true // Option 3581+```582+583+For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.584+585+When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.586+587+Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:588+589+```js590+const state = {591+ set: new Set(),592+ map: new Map()593+}594+const nextState = produce(state, draft => {595+ // Don't use any Set methods, as that mutates the instance!596+ draft.set.add("foo") // ❌597+598+ // 1. Instead, clone the set (just once)599+ const newSet = new Set(draft.set) // ✅600+601+ // 2. Mutate the clone (just in this producer)602+ newSet.add("foo")603+604+ // 3. Update the draft with the new set605+ draft.set = newSet606+607+ // Similarly, don't use any Map methods.608+ draft.map.set("foo", "bar") // ❌609+610+ // 1. Instead, clone the map (just once)611+ const newMap = new Map(draft.map) // ✅612+613+ // 2. Mutate it614+ newMap.set("foo", "bar")615+616+ // 3. Update the draft617+ draft.map = newMap618+})619+```620+621+## TypeScript or Flow622+623+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.624+625+The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:626+627+```ts628+import produce from "immer"629+630+interface State {631+ readonly x: number632+}633+634+// `x` cannot be modified here635+const state: State = {636+ x: 0637+}638+639+const newState = produce(state, draft => {640+ // `x` can be modified here641+ draft.x++642+})643+644+// `newState.x` cannot be modified here645+```646+647+This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!648+649+For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:650+651+```ts652+import produce, {Draft} from "immer"653+654+interface State {655+ readonly x: number656+}657+658+// `x` cannot be modified here659+const state: State = {660+ x: 0661+}662+663+const increment = produce((draft: Draft<State>, inc: number) => {664+ // `x` can be modified here665+ draft.x += inc666+})667+668+const newState = increment(state, 2)669+// `newState.x` cannot be modified here670+```671+672+**Note:** Immer v1.9+ supports TypeScript v3.1+ only.673+674+**Note:** Immer v3.0+ supports TypeScript v3.4+ only.675+676+# Pitfalls677+678+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).679+1. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.680+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`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.681+1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`682+1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.683+684+## Cool things built with immer685+686+- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_687+- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_688+- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_689+- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_690+- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_691+- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_692+- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_693+- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_694+- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse React (useReducer()) and Redux reducers with Typescript_695+- [redux-ts-utils](https://github.com/knpwrs/redux-ts-utils) _Everything you need to create type-safe applications with Redux with a strong emphasis on simplicity_696+- [react-state-tree](https://github.com/suchipi/react-state-tree) _Drop-in replacement for useState that persists your state into a redux-like state tree_697+- [redux-immer](https://github.com/salvoravida/redux-immer) _is used to create an equivalent function of Redux combineReducers that works with `immer` state. Like `redux-immutable` but for `immer`_698+- ... and [many more](https://www.npmjs.com/browse/depended/immer)699+700+## How does Immer work?701+702+Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).703+704+## Example patterns.705+706+_For those who have to go back to thinking in object updates :-)_707+708+```javascript709+import produce from "immer"710+711+// object mutations712+const todosObj = {713+ id1: {done: false, body: "Take out the trash"},714+ id2: {done: false, body: "Check Email"}715+}716+717+// add718+const addedTodosObj = produce(todosObj, draft => {719+ draft["id3"] = {done: false, body: "Buy bananas"}720+})721+722+// delete723+const deletedTodosObj = produce(todosObj, draft => {724+ delete draft["id1"]725+})726+727+// update728+const updatedTodosObj = produce(todosObj, draft => {729+ draft["id1"].done = true730+})731+732+// array mutations733+const todosArray = [734+ {id: "id1", done: false, body: "Take out the trash"},735+ {id: "id2", done: false, body: "Check Email"}736+]737+738+// add739+const addedTodosArray = produce(todosArray, draft => {740+ draft.push({id: "id3", done: false, body: "Buy bananas"})741+})742+743+// delete744+const deletedTodosArray = produce(todosArray, draft => {745+ draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)746+ // or (slower):747+ // return draft.filter(todo => todo.id !== "id1")748+})749+750+// update751+const updatedTodosArray = produce(todosArray, draft => {752+ draft[draft.findIndex(todo => todo.id === "id1")].done = true753+})754+```755+756+## Performance757+758+Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items and updates 5,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.759+760+These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.761+762+763+764+Most important observation:765+766+- Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.767+- Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)768+- Generating patches doesn't significantly slow immer down769+- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.770+771+## Migration772+773+**Immer 2.\* -> 3.0**774+775+In your producers, make sure you're not treating `this` as the draft. (see here: https://github.com/immerjs/immer/issues/308)776+777+Upgrade to `typescript@^3.4` if you're a TypeScript user.778+779+**Immer 1.\* -> 2.0**780+781+Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.782+783+**Immer 2.1 -> 2.2**784+785+When using TypeScript, for curried reducers that are typed in the form `produce<Type>((arg) => { })`, rewrite this to `produce((arg: Type) => { })` or `produce((arg: Draft<Type>) => { })` for correct inference.786+787+## FAQ788+789+_(for those who skimmed the above instead of actually reading)_790+791+**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**792+793+A: Yes794+795+**Q: Does Immer support deep updates?**796+797+A: Yes798+799+**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**800+801+A: Yes802+803+**Q: Can I typecheck my data structures when using Immer?**804+805+A: Yes806+807+**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**808+809+A: Yes810+811+**Q: Is it fast?**812+813+A: Yes814+815+**Q: Idea! Can Immer freeze the state for me?**816+817+A: Yes818+819+## Credits820+821+Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.822+823+## Donations824+825+A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)deleted:docs/doc2.md-7 removed
1234567---id: doc2title: document number 2---
This is a link to [another document.](doc3.md) This is a link to an [external page.](http://www.example.com)deleted:docs/doc3.md-14 removed
1234567891011121314---id: doc3title: This is document number 3---
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ac euismod odio, eu consequat dui. Nullam molestie consectetur risus id imperdiet. Proin sodales ornare turpis, non mollis massa ultricies id. Nam at nibh scelerisque, feugiat ante non, dapibus tortor. Vivamus volutpat diam quis tellus elementum bibendum. Praesent semper gravida velit quis aliquam. Etiam in cursus neque. Nam lectus ligula, malesuada et mauris a, bibendum faucibus mi. Phasellus ut interdum felis. Phasellus in odio pulvinar, porttitor urna eget, fringilla lectus. Aliquam sollicitudin est eros. Mauris consectetur quam vitae mauris interdum hendrerit. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Duis et egestas libero, imperdiet faucibus ipsum. Sed posuere eget urna vel feugiat. Vivamus a arcu sagittis, fermentum urna dapibus, congue lectus. Fusce vulputate porttitor nisl, ac cursus elit volutpat vitae. Nullam vitae ipsum egestas, convallis quam non, porta nibh. Morbi gravida erat nec neque bibendum, eu pellentesque velit posuere. Fusce aliquam erat eu massa eleifend tristique.
Sed consequat sollicitudin ipsum eget tempus. Integer a aliquet velit. In justo nibh, pellentesque non suscipit eget, gravida vel lacus. Donec odio ante, malesuada in massa quis, pharetra tristique ligula. Donec eros est, tristique eget finibus quis, semper non nisl. Vivamus et elit nec enim ornare placerat. Sed posuere odio a elit cursus sagittis.
Phasellus feugiat purus eu tortor ultrices finibus. Ut libero nibh, lobortis et libero nec, dapibus posuere eros. Sed sagittis euismod justo at consectetur. Nulla finibus libero placerat, cursus sapien at, eleifend ligula. Vivamus elit nisl, hendrerit ac nibh eu, ultrices tempus dui. Nam tellus neque, commodo non rhoncus eu, gravida in risus. Nullam id iaculis tortor.
Nullam at odio in sem varius tempor sit amet vel lorem. Etiam eu hendrerit nisl. Fusce nibh mauris, vulputate sit amet ex vitae, congue rhoncus nisl. Sed eget tellus purus. Nullam tempus commodo erat ut tristique. Cras accumsan massa sit amet justo consequat eleifend. Integer scelerisque vitae tellus id consectetur.deleted:docs/exampledoc4.md-6 removed
123456---id: doc4title: Other Document---
this is another documentdeleted:docs/exampledoc5.md-6 removed
123456---id: doc5title: Fifth Document---
Another onemodified:website/i18n/en.json+2 added-15 removed
1234566789101112131415161718192021221112131415282916171819209 unmodified lines{ "_comment": "This file is auto-generated by write-translations.js", "localized-strings": { "next": "Next", "previous": "Previous", "tagline": "A website for testing", "tagline": "Create the next immutable state by mutating the current one", "docs": { "doc1": { "title": "Latin-ish", "sidebar_label": "Example Page" }, "doc2": { "title": "document number 2" }, "doc3": { "title": "This is document number 3" }, "doc4": { "title": "Other Document" }, "doc5": { "title": "Fifth Document" } }, "links": { "Docs": "Docs", "API": "API", "Help": "Help", "Blog": "Blog" "Help": "Help" }, "categories": { "Docusaurus": "Docusaurus", "First Category": "First Category",9 unmodified linesmodified:website/siteConfig.js+11 added-31 removed
6 unmodified lines78910111213141516171819202122112425262712131415161718192033342122232425262740414243444528294748493031323334353657583738394041429 unmodified lines52535455765657585980606162636426 unmodified lines6 unmodified lines
// See https://docusaurus.io/docs/site-config for all the possible// site configuration options.
// List of projects/orgs using your project for the users page.const users = [ { caption: "User1", // You will need to prepend the image path with your baseUrl // if it is not '/', like: '/test-site/img/image.jpg'. image: "/img/undraw_open_source.svg", infoLink: "https://www.facebook.com", pinned: true }]
const siteConfig = { title: "Test Site", // Title for your website. tagline: "A website for testing", url: "https://your-docusaurus-test-site.com", // Your website URL baseUrl: "/", // Base URL for your project */ title: "Immer", // Title for your website. tagline: "Create the next immutable state by mutating the current one", url: "https://immerjs.github.io", // Your website URL baseUrl: "/immer/", // Base URL for your project */ // For github.io type URLs, you would set the url and baseUrl like: // url: 'https://facebook.github.io', // baseUrl: '/test-site/',
// Used for publishing and more projectName: "test-site", organizationName: "facebook", projectName: "immer", organizationName: "immerjs", // For top-level user or org sites, the organization is still the same. // e.g., for the https://JoelMarcey.github.io site, it would be set like... // organizationName: 'JoelMarcey'
// For no header links in the top nav bar -> headerLinks: [], headerLinks: [ {doc: "doc1", label: "Docs"}, {doc: "doc4", label: "API"}, {page: "help", label: "Help"}, {blog: true, label: "Blog"} ], headerLinks: [{doc: "doc1", label: "Docs"}, {page: "help", label: "Help"}],
// If you have users set above, you add it here: users,
/* path to images for header/footer */ headerIcon: "img/favicon.ico", footerIcon: "img/favicon.ico", favicon: "img/favicon.ico",
/* Colors for website */ colors: { primaryColor: "#11220f", secondaryColor: "#0b170a" primaryColor: "#000", secondaryColor: "#22e7c3" },
/* Custom fonts for website */ /*9 unmodified lines }, */
// This copyright info is used in /core/Footer.js and blog RSS/Atom feeds. copyright: `Copyright © ${new Date().getFullYear()} Your Name or Your Company Name`, copyright: `Copyright © ${new Date().getFullYear()} Michel Weststrate`,
highlight: { // Highlight.js theme to use for syntax highlighting in code blocks. theme: "default" theme: "dracula" },
// Add custom scripts here that would be placed in <script> tags. scripts: ["https://buttons.github.io/buttons.js"],26 unmodified linesmodified:readme.md-820 removed
11 unmodified lines12 13 Did Immer make a difference to your project? Consider buying me a coffee!<br/><a href="https://www.buymeacoffee.com/mweststrate" target="_blank"><img src="https://www.buymeacoffee.com/assets/img/custom_images/orange_img.png" alt="Buy Me A Coffee" style="height: auto !important;width: auto !important;" ></a>14 15 ---16-17-- NPM: `npm install immer`18-- Yarn: `yarn add immer`19-- CDN: Exposed global is `immer`20- - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`21- - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`22-23----24-25-- 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)26-- Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)27-28-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.29-30-The basic idea is that you will apply all your changes to a temporary _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.31-32-33-34-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).35-36-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.37-38-## External resources39-40-- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)41-- Blog: by Workday Prism on why they picked Immer to manage immutable state [The Search for a Strongly-Typed, Immutable State](https://medium.com/workday-engineering/workday-prism-analytics-the-search-for-a-strongly-typed-immutable-state-a09f6768b2b5)42-- Blog: [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)43-- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)44-- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate45-- [ForwardJS 2019: Immutability is Changing - From Immutable.js to Immer](https://www.youtube.com/watch?v=bFuRvcAEiHg&feature=youtu.be) by [shawn swyx wang](https://twitter.com/swyx/)46-47-## API48-49-The Immer package exposes a default function that does all the work.50-51-`produce(currentState, producer: (draftState) => void): nextState`52-53-There is also a curried overload that is explained [below](#currying).54-55-## Example56-57-```javascript58-import produce from "immer"59-60-const baseState = [61- {62- todo: "Learn typescript",63- done: true64- },65- {66- todo: "Try immer",67- done: false68- }69-]70-71-const nextState = produce(baseState, draftState => {72- draftState.push({todo: "Tweet about it"})73- draftState[1].done = true74-})75-```76-77-The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.78-79-```javascript80-// the new item is only added to the next state,81-// base state is unmodified82-expect(baseState.length).toBe(2)83-expect(nextState.length).toBe(3)84-85-// same for the changed 'done' prop86-expect(baseState[1].done).toBe(false)87-expect(nextState[1].done).toBe(true)88-89-// unchanged data is structurally shared90-expect(nextState[0]).toBe(baseState[0])91-// changed data not (dûh)92-expect(nextState[1]).not.toBe(baseState[1])93-```94-95-## Benefits96-97-- Immutability with normal JavaScript objects and arrays. No new APIs to learn!98-- Strongly typed, no string based paths selectors etc.99-- Structural sharing out of the box100-- Object freezing out of the box101-- Deep updates are a breeze102-- Boilerplate reduction. Less noise, more concise code.103-- Small [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)104-105-Read further to see all these benefits explained.106-107-## Reducer Example108-109-Here is a simple example of the difference that Immer could make in practice.110-111-```javascript112-// Redux reducer113-// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js114-const byId = (state, action) => {115- switch (action.type) {116- case RECEIVE_PRODUCTS:117- return {118- ...state,119- ...action.products.reduce((obj, product) => {120- obj[product.id] = product121- return obj122- }, {})123- }124- default:125- return state126- }127-}128-```129-130-After using Immer, that simply becomes:131-132-```javascript133-import produce from "immer"134-135-const byId = (state, action) =>136- produce(state, draft => {137- switch (action.type) {138- case RECEIVE_PRODUCTS:139- action.products.forEach(product => {140- draft[product.id] = product141- })142- }143- })144-```145-146-Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.147-148-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).149-150-_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._151-152-## React.setState example153-154-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)):155-156-```javascript157-/**158- * Classic React.setState with a deep merge159- */160-onBirthDayClick1 = () => {161- this.setState(prevState => ({162- user: {163- ...prevState.user,164- age: prevState.user.age + 1165- }166- }))167-}168-169-/**170- * ...But, since setState accepts functions,171- * we can just create a curried producer and further simplify!172- */173-onBirthDayClick2 = () => {174- this.setState(175- produce(draft => {176- draft.user.age += 1177- })178- )179-}180-```181-182-## Currying183-184-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.185-186-For example:187-188-```javascript189-// mapper will be of signature (state, index) => state190-const mapper = produce((draft, index) => {191- draft.index = index192-})193-194-// example usage195-console.dir([{}, {}, {}].map(mapper))196-//[{index: 0}, {index: 1}, {index: 2}])197-```198-199-This mechanism can also nicely be leveraged to further simplify our example reducer:200-201-```javascript202-import produce from "immer"203-204-const byId = produce((draft, action) => {205- switch (action.type) {206- case RECEIVE_PRODUCTS:207- action.products.forEach(product => {208- draft[product.id] = product209- })210- return211- }212-})213-```214-215-Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).216-217-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`:218-219-```javascript220-import produce from "immer"221-222-const byId = produce(223- (draft, action) => {224- switch (action.type) {225- case RECEIVE_PRODUCTS:226- action.products.forEach(product => {227- draft[product.id] = product228- })229- return230- }231- },232- {233- 1: {id: 1, name: "product-1"}234- }235-)236-```237-238-##### Fun with currying239-240-A random fun example just for inspiration: a neat trick is to turn `Object.assign` into a producer to create a "spread" function that is smarter than the normal spread operator, as it doesn't produce a new state if the result doesn't actually change ([details & explanation](https://twitter.com/mweststrate/status/1045059430256119809)). Quick example:241-242-```javascript243-import produce from "immer"244-const spread = produce(Object.assign)245-246-const base = {x: 1, y: 1}247-248-console.log({...base, y: 1} === base) // false249-console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced250-console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should251-```252-253-## Patches254-255-During the run of a producer, Immer can record all the patches that would replay the changes made by the reducer. This is a very powerful tool if you want to fork your state temporarily and replay the changes to the original.256-257-Patches are useful in few scenarios:258-259-- To exchange incremental updates with other parties, for example over websockets260-- For debugging / traces, to see precisely how state is changed over time261-- As basis for undo/redo or as an approach to replay changes on a slightly different state tree262-263-To help with replaying patches, `applyPatches` comes in handy. Here is an example how patches could be used to record the incremental updates and (inverse) apply them:264-265-```javascript266-import produce, {applyPatches} from "immer"267-268-let state = {269- name: "Micheal",270- age: 32271-}272-273-// Let's assume the user is in a wizard, and we don't know whether274-// his changes should end up in the base state ultimately or not...275-let fork = state276-// all the changes the user made in the wizard277-let changes = []278-// the inverse of all the changes made in the wizard279-let inverseChanges = []280-281-fork = produce(282- fork,283- draft => {284- draft.age = 33285- },286- // The third argument to produce is a callback to which the patches will be fed287- (patches, inversePatches) => {288- changes.push(...patches)289- inverseChanges.push(...inversePatches)290- }291-)292-293-// In the meantime, our original state is replaced, as, for example,294-// some changes were received from the server295-state = produce(state, draft => {296- draft.name = "Michel"297-})298-299-// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!300-state = applyPatches(state, changes)301-302-// state now contains the changes from both code paths!303-expect(state).toEqual({304- name: "Michel", // changed by the server305- age: 33 // changed by the wizard306-})307-308-// Finally, even after finishing the wizard, the user might change his mind and undo his changes...309-state = applyPatches(state, inverseChanges)310-expect(state).toEqual({311- name: "Michel", // Not reverted312- age: 32 // Reverted313-})314-```315-316-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. 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:317-318-```json319-[320- {321- "op": "replace",322- "path": ["profile"],323- "value": {"name": "Veria", "age": 5}324- },325- {"op": "remove", "path": ["tags", 3]}326-]327-```328-329-```json330-[331- {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},332- {"op": "add", "path": ["tags", 3], "value": "kiddo"}333-]334-```335-336-### `produceWithPatches`337-338-Instead of setting up a patch listener, an easier way to obtain the patches is to use `produceWithPatches`, which has the same signature as `produce`, except that it doesn't return just the next state, but a tuple consisting of `[nextState, patches, inversePatches]`. Like `produce`, `produceWithPatches` supports currying as well.339-340-```javascript341-import {produceWithPatches} from "immer"342-343-const [nextState, patches, inversePatches] = produceWithPatches(344- {345- age: 33346- },347- draft => {348- draft.age++349- }350-)351-```352-353-Which produces:354-355-```javascript356-;[357- {358- age: 34359- },360- [361- {362- op: "replace",363- path: ["age"],364- value: 34365- }366- ],367- [368- {369- op: "replace",370- path: ["age"],371- value: 33372- }373- ]374-]375-```376-377-For a more in-depth study, see [Distributing patches and rebasing actions using Immer](https://medium.com/@mweststrate/distributing-state-changes-using-snapshots-patches-and-actions-part-2-2f50d8363988)378-379-Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.380-381-## Async producers382-383-It is allowed to return Promise objects from recipes. Or, in other words, to use `async / await`. This can be pretty useful for long running processes, that only produce the new object once the promise chain resolves. Note that `produce` itself (even in the curried form) will return a promise if the producer is async. Example:384-385-```javascript386-import produce from "immer"387-388-const user = {389- name: "michel",390- todos: []391-}392-393-const loadedUser = await produce(user, async function(draft) {394- draft.todos = await (await window.fetch("http://host/" + draft.name)).json()395-})396-```397-398-_Warning: please note that the draft shouldn't be 'leaked' from the async process and stored else where. The draft will still be revoked as soon as the async process completes._399-400-## `createDraft` and `finishDraft`401-402-`createDraft` and `finishDraft` are two low-level functions that are mostly useful for libraries that build abstractions on top of immer. It avoids the need to always create a function in order to work with drafts. Instead, one can create a draft, modify it, and at some time in the future finish the draft, in which case the next immutable state will be produced. We could for example rewrite our above example as:403-404-```javascript405-import {createDraft, finishDraft} from "immer"406-407-const user = {408- name: "michel",409- todos: []410-}411-412-const draft = createDraft(user)413-draft.todos = await (await window.fetch("http://host/" + draft.name)).json()414-const loadedUser = finishDraft(draft)415-```416-417-Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.418-419-_Warning: in general, we recommend to use `produce` instead of the `createDraft` / `finishDraft` combo, `produce` is less error prone in usage, and more clearly separates the concepts of mutability and immutability in your code base._420-421-## Returning data from producers422-423-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`.424-425-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:426-427-```javascript428-const userReducer = produce((draft, action) => {429- switch (action.type) {430- case "renameUser":431- // OK: we modify the current state432- draft.users[action.payload.id].name = action.payload.name433- return draft // same as just 'return'434- case "loadUsers":435- // OK: we return an entirely new state436- return action.payload437- case "adduser-1":438- // NOT OK: This doesn't do change the draft nor return a new state!439- // It doesn't modify the draft (it just redeclares it)440- // In fact, this just doesn't do anything at all441- draft = {users: [...draft.users, action.payload]}442- return443- case "adduser-2":444- // NOT OK: modifying draft *and* returning a new state445- draft.userCount += 1446- return {users: [...draft.users, action.payload]}447- case "adduser-3":448- // OK: returning a new state. But, unnecessary complex and expensive449- return {450- userCount: draft.userCount + 1,451- users: [...draft.users, action.payload]452- }453- case "adduser-4":454- // OK: the immer way455- draft.userCount += 1456- draft.users.push(action.payload)457- return458- }459-})460-```461-462-_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._463-464-## Producing `undefined` using `nothing`465-466-So, in general, one can replace the current state by just `return`ing a new value from the producer, rather than modifying the draft. There is a subtle edge case however: if you try to write a producer that wants to replace the current state with `undefined`:467-468-```javascript469-produce({}, draft => {470- // don't do anything471-})472-```473-474-Versus:475-476-```javascript477-produce({}, draft => {478- // Try to return undefined from the producer479- return undefined480-})481-```482-483-The problem is that in JavaScript a function that doesn't return anything also returns `undefined`! So immer cannot differentiate between those different cases. So, by default, Immer will assume that any producer that returns `undefined` just tried to modify the draft.484-485-However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:486-487-```javascript488-import produce, {nothing} from "immer"489-490-const state = {491- hello: "world"492-}493-494-produce(state, draft => {})495-produce(state, draft => undefined)496-// Both return the original state: { hello: "world"}497-498-produce(state, draft => nothing)499-// Produces a new state, 'undefined'500-```501-502-N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.503-504-## Inline shortcuts using `void`505-506-Draft mutations in Immer usually warrant a code block, since a return denotes an overwrite. Sometimes that can stretch code a little more than you might be comfortable with.507-508-In such cases, you can use javascripts [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void) operator, which evaluates expressions and returns `undefined`.509-510-```javascript511-// Single mutation512-produce(draft => void (draft.user.age += 1))513-514-// Multiple mutations515-produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))516-```517-518-Code style is highly personal, but for code bases that are to be understood by many, we recommend to stick to the classic `draft => { draft.user.age += 1}` to avoid cognitive overhead.519-520-## Extracting the original object from a proxied instance521-522-Immer exposes a named export `original` that will get the original object from the proxied instance inside `produce` (or return `undefined` for unproxied values). A good example of when this can be useful is when searching for nodes in a tree-like state using strict equality.523-524-```js525-import {original} from "immer"526-527-const baseState = {users: [{name: "Richie"}]}528-const nextState = produce(baseState, draftState => {529- original(draftState.users) // is === baseState.users530-})531-```532-533-Just want to know if a value is a proxied instance? Use the `isDraft` function!534-535-```js536-import {isDraft} from "immer"537-538-const baseState = {users: [{name: "Bobby"}]}539-const nextState = produce(baseState, draft => {540- isDraft(draft) // => true541- isDraft(draft.users) // => true542- isDraft(draft.users[0]) // => true543-})544-isDraft(nextState) // => false545-```546-547-## Auto freezing548-549-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.550-551-_⚠️ If auto freezing is enabled, recipes are not entirely side-effect free: Any plain object or array that ends up in the produced result, will be frozen, even when these objects were not frozen before the start of the producer! ⚠️_552-553-## Immer on older JavaScript environments?554-555-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 (< v0.59) on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.556-557-## Importing immer558-559-`produce` is exposed as the default export, but optionally it can be used as name import as well, as this benefits some older project setups. So the following imports are all correct, where the first is recommended:560-561-```javascript562-import produce from "immer"563-import {produce} from "immer"564-565-const {produce} = require("immer")566-const produce = require("immer").produce567-const produce = require("immer").default568-569-import unleashTheMagic from "immer"570-import {produce as unleashTheMagic} from "immer"571-```572-573-## Supported object types574-575-Plain objects and arrays are always drafted by Immer.576-577-Every other object must use the `immerable` symbol to mark itself as compatible with Immer. When one of these objects is mutated within a producer, its prototype is preserved between copies.578-579-```js580-import {immerable} from "immer"581-582-class Foo {583- [immerable] = true // Option 1584-585- constructor() {586- this[immerable] = true // Option 2587- }588-}589-590-Foo[immerable] = true // Option 3591-```592-593-For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.594-595-When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.596-597-Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:598-599-```js600-const state = {601- set: new Set(),602- map: new Map()603-}604-const nextState = produce(state, draft => {605- // Don't use any Set methods, as that mutates the instance!606- draft.set.add("foo") // ❌607-608- // 1. Instead, clone the set (just once)609- const newSet = new Set(draft.set) // ✅610-611- // 2. Mutate the clone (just in this producer)612- newSet.add("foo")613-614- // 3. Update the draft with the new set615- draft.set = newSet616-617- // Similarly, don't use any Map methods.618- draft.map.set("foo", "bar") // ❌619-620- // 1. Instead, clone the map (just once)621- const newMap = new Map(draft.map) // ✅622-623- // 2. Mutate it624- newMap.set("foo", "bar")625-626- // 3. Update the draft627- draft.map = newMap628-})629-```630-631-## TypeScript or Flow632-633-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.634-635-The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:636-637-```ts638-import produce from "immer"639-640-interface State {641- readonly x: number642-}643-644-// `x` cannot be modified here645-const state: State = {646- x: 0647-}648-649-const newState = produce(state, draft => {650- // `x` can be modified here651- draft.x++652-})653-654-// `newState.x` cannot be modified here655-```656-657-This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!658-659-For curried reducers, the type is inferred from the first argument of recipe function, so make sure to type it. The `Draft` utility type can be used if the state argument type is immutable:660-661-```ts662-import produce, {Draft} from "immer"663-664-interface State {665- readonly x: number666-}667-668-// `x` cannot be modified here669-const state: State = {670- x: 0671-}672-673-const increment = produce((draft: Draft<State>, inc: number) => {674- // `x` can be modified here675- draft.x += inc676-})677-678-const newState = increment(state, 2)679-// `newState.x` cannot be modified here680-```681-682-**Note:** Immer v1.9+ supports TypeScript v3.1+ only.683-684-**Note:** Immer v3.0+ supports TypeScript v3.4+ only.685-686-# Pitfalls687-688-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).689-1. Immer assumes your state to be a unidirectional tree. That is, no object should appear twice in the tree, and there should be no circular references.690-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`. Also, realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones. Also note that `original` can be used to get the original state of an object, which is cheaper to read.691-1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower than `produce(base, d => { for (let x of y) d.push(x)})`692-1. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.693-694-## Cool things built with immer695-696-- [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_697-- [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_698-- [immer based handleActions](https://gist.github.com/kitze/fb65f527803a93fb2803ce79a792fff8) _Boilerplate free actions for Redux_699-- [redux-box](https://github.com/anish000kumar/redux-box) _Modular and easy-to-grasp redux based state management, with least boilerplate_700-- [quick-redux](https://github.com/jeffreyyoung/quick-redux) _tools to make redux development quicker and easier_701-- [bey](https://github.com/jamiebuilds/bey) _Simple immutable state for React using Immer_702-- [immer-wieder](https://github.com/drcmda/immer-wieder#readme) _State management lib that combines React 16 Context and immer for Redux semantics_703-- [robodux](https://github.com/neurosnap/robodux) _flexible way to reduce redux boilerplate_704-- [immer-reducer](https://github.com/epeli/immer-reducer) _Type-safe and terse React (useReducer()) and Redux reducers with Typescript_705-- [redux-ts-utils](https://github.com/knpwrs/redux-ts-utils) _Everything you need to create type-safe applications with Redux with a strong emphasis on simplicity_706-- [react-state-tree](https://github.com/suchipi/react-state-tree) _Drop-in replacement for useState that persists your state into a redux-like state tree_707-- [redux-immer](https://github.com/salvoravida/redux-immer) _is used to create an equivalent function of Redux combineReducers that works with `immer` state. Like `redux-immutable` but for `immer`_708-- ... and [many more](https://www.npmjs.com/browse/depended/immer)709-710-## How does Immer work?711-712-Read the (second part of the) [introduction blog](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3).713-714-## Example patterns.715-716-_For those who have to go back to thinking in object updates :-)_717-718-```javascript719-import produce from "immer"720-721-// object mutations722-const todosObj = {723- id1: {done: false, body: "Take out the trash"},724- id2: {done: false, body: "Check Email"}725-}726-727-// add728-const addedTodosObj = produce(todosObj, draft => {729- draft["id3"] = {done: false, body: "Buy bananas"}730-})731-732-// delete733-const deletedTodosObj = produce(todosObj, draft => {734- delete draft["id1"]735-})736-737-// update738-const updatedTodosObj = produce(todosObj, draft => {739- draft["id1"].done = true740-})741-742-// array mutations743-const todosArray = [744- {id: "id1", done: false, body: "Take out the trash"},745- {id: "id2", done: false, body: "Check Email"}746-]747-748-// add749-const addedTodosArray = produce(todosArray, draft => {750- draft.push({id: "id3", done: false, body: "Buy bananas"})751-})752-753-// delete754-const deletedTodosArray = produce(todosArray, draft => {755- draft.splice(draft.findIndex(todo => todo.id === "id1"), 1)756- // or (slower):757- // return draft.filter(todo => todo.id !== "id1")758-})759-760-// update761-const updatedTodosArray = produce(todosArray, draft => {762- draft[draft.findIndex(todo => todo.id === "id1")].done = true763-})764-```765-766-## Performance767-768-Here is a [simple benchmark](__performance_tests__/todo.js) on the performance of Immer. This test takes 50,000 todo items and updates 5,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.769-770-These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.771-772-773-774-Most important observation:775-776-- Immer with proxies is roughly speaking twice to three times slower as a handwritten reducer (the above test case is worst case, see `yarn test:perf` for more tests). This is in practice negligible.777-- Immer is roughly as fast as ImmutableJS. However, the _immutableJS + toJS_ makes clear the cost that often needs to be paid later; converting the immutableJS objects back to plain objects, to be able to pass them to components, over the network etc... (And there is also the upfront cost of converting data received from e.g. the server to immutable JS)778-- Generating patches doesn't significantly slow immer down779-- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.780-781-## Migration782-783-**Immer 2.\* -> 3.0**784-785-In your producers, make sure you're not treating `this` as the draft. (see here: https://github.com/immerjs/immer/issues/308)786-787-Upgrade to `typescript@^3.4` if you're a TypeScript user.788-789-**Immer 1.\* -> 2.0**790-791-Make sure you don't return any promises as state, because `produce` will actually invoke the promise and wait until it settles.792-793-**Immer 2.1 -> 2.2**794-795-When using TypeScript, for curried reducers that are typed in the form `produce<Type>((arg) => { })`, rewrite this to `produce((arg: Type) => { })` or `produce((arg: Draft<Type>) => { })` for correct inference.796-797-## FAQ798-799-_(for those who skimmed the above instead of actually reading)_800-801-**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**802-803-A: Yes804-805-**Q: Does Immer support deep updates?**806-807-A: Yes808-809-**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**810-811-A: Yes812-813-**Q: Can I typecheck my data structures when using Immer?**814-815-A: Yes816-817-**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**818-819-A: Yes820-821-**Q: Is it fast?**822-823-A: Yes824-825-**Q: Idea! Can Immer freeze the state for me?**826-827-A: Yes828-829-## Credits830-831-Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.832-833-## Donations834-835-A significant part of my OSS work is unpaid. So [donations](https://mobx.js.org/donate.html) are greatly appreciated :)