Skip to content
Myr

Docs 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 79ec197 · Browse files · 48 files+949 added−1190 removed
This commit

State

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

Diff stats

48 files+949 added−1190 removed

  • other:+949 added−1190 removed

48 files+949 added−1190 removed

added:docs/api.md+8 added
added:docs/async.md+45 added
added:docs/built-with.md+6 added
added:docs/complex-objects.md+62 added
added:docs/curried-produce.md+75 added
modified:docs/doc1.md+2 added-697 removed
2 unmodified lines
3title: Latin-ish4sidebar_label: Example Page5---67<div id="codefund"><!-- fallback content --></div>89- NPM: `npm install immer`10- Yarn: `yarn add immer`11- CDN: Exposed global is `immer`12 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`13 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`1415---1615- 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)1718Immer (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.1920The 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.2122![immer-hd.png](images/hd/immer.png)2324Using 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).2526A 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.2717## External resources1819- Blog: [The Rise of Immer in React](https://www.netlify.com/blog/2018/09/12/the-rise-of-immer-in-react/)20- 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)
1 unmodified line
22- Video tutorial: [Using Immer with React.setState](https://codedaily.io/screencasts/86/Immutable-Data-with-Immer-and-React-setState)23- [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate24- [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/)2537## API3839The Immer package exposes a default function that does all the work.4041`produce(currentState, producer: (draftState) => void): nextState`4243There is also a curried overload that is explained [below](#currying).4445## Example4647```javascript48import produce from "immer"4950const baseState = [51 {52 todo: "Learn typescript",53 done: true54 },55 {56 todo: "Try immer",57 done: false58 }59]6061const nextState = produce(baseState, draftState => {62 draftState.push({todo: "Tweet about it"})63 draftState[1].done = true64})65```6667The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.6869```javascript70// the new item is only added to the next state,71// base state is unmodified72expect(baseState.length).toBe(2)73expect(nextState.length).toBe(3)7475// same for the changed 'done' prop76expect(baseState[1].done).toBe(false)77expect(nextState[1].done).toBe(true)7879// unchanged data is structurally shared80expect(nextState[0]).toBe(baseState[0])81// changed data not (dûh)82expect(nextState[1]).not.toBe(baseState[1])83```8485## Benefits8687- 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 [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)9495Read further to see all these benefits explained.9697## Reducer Example9899Here is a simple example of the difference that Immer could make in practice.100101```javascript102// Redux reducer103// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.js104const 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```119120After using Immer, that simply becomes:121122```javascript123import produce from "immer"124125const 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```135136Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.137138Creating 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).139140_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._141142## React.setState example143144Deep 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)):145146```javascript147/**148 * Classic React.setState with a deep merge149 */150onBirthDayClick1 = () => {151 this.setState(prevState => ({152 user: {153 ...prevState.user,154 age: prevState.user.age + 1155 }156 }))157}158159/**160 * ...But, since setState accepts functions,161 * we can just create a curried producer and further simplify!162 */163onBirthDayClick2 = () => {164 this.setState(165 produce(draft => {166 draft.user.age += 1167 })168 )169}170```171172## Currying173174Passing 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.175176For example:177178```javascript179// mapper will be of signature (state, index) => state180const mapper = produce((draft, index) => {181 draft.index = index182})183184// example usage185console.dir([{}, {}, {}].map(mapper))186//[{index: 0}, {index: 1}, {index: 2}])187```188189This mechanism can also nicely be leveraged to further simplify our example reducer:190191```javascript192import produce from "immer"193194const 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```204205Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).206207If you want to initialize an uninitialized state using this construction, you can do so by passing the initial state as second argument to `produce`:208209```javascript210import produce from "immer"211212const 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```227228##### Fun with currying229230A 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:231232```javascript233import produce from "immer"234const spread = produce(Object.assign)235236const base = {x: 1, y: 1}237238console.log({...base, y: 1} === base) // false239console.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was produced240console.log(spread(base, {y: 2}) === base) // false, produced a new object as it should241```242243## Patches244245During 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.246247Patches are useful in few scenarios:248249- 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 tree252253To 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:254255```javascript256import produce, {applyPatches} from "immer"257258let state = {259 name: "Micheal",260 age: 32261}262263// 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...265let fork = state266// all the changes the user made in the wizard267let changes = []268// the inverse of all the changes made in the wizard269let inverseChanges = []270271fork = 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)282283// In the meantime, our original state is replaced, as, for example,284// some changes were received from the server285state = produce(state, draft => {286 draft.name = "Michel"287})288289// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!290state = applyPatches(state, changes)291292// state now contains the changes from both code paths!293expect(state).toEqual({294 name: "Michel", // changed by the server295 age: 33 // changed by the wizard296})297298// Finally, even after finishing the wizard, the user might change his mind and undo his changes...299state = applyPatches(state, inverseChanges)300expect(state).toEqual({301 name: "Michel", // Not reverted302 age: 32 // Reverted303})304```305306The 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:307308```json309[310 {311 "op": "replace",312 "path": ["profile"],313 "value": {"name": "Veria", "age": 5}314 },315 {"op": "remove", "path": ["tags", 3]}316]317```318319```json320[321 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},322 {"op": "add", "path": ["tags", 3], "value": "kiddo"}323]324```325326### `produceWithPatches`327328Instead 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.329330```javascript331import {produceWithPatches} from "immer"332333const [nextState, patches, inversePatches] = produceWithPatches(334 {335 age: 33336 },337 draft => {338 draft.age++339 }340)341```342343Which produces:344345```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```366367For 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)368369Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.370371## Async producers372373It 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:374375```javascript376import produce from "immer"377378const user = {379 name: "michel",380 todos: []381}382383const loadedUser = await produce(user, async function(draft) {384 draft.todos = await (await window.fetch("http://host/" + draft.name)).json()385})386```387388_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._389390## `createDraft` and `finishDraft`391392`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:393394```javascript395import {createDraft, finishDraft} from "immer"396397const user = {398 name: "michel",399 todos: []400}401402const draft = createDraft(user)403draft.todos = await (await window.fetch("http://host/" + draft.name)).json()404const loadedUser = finishDraft(draft)405```406407Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.408409_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._410411## Returning data from producers412413It 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`.414415It 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:416417```javascript418const 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```451452_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._453454## Producing `undefined` using `nothing`455456So, 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`:457458```javascript459produce({}, draft => {460 // don't do anything461})462```463464Versus:465466```javascript467produce({}, draft => {468 // Try to return undefined from the producer469 return undefined470})471```472473The 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.474475However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:476477```javascript478import produce, {nothing} from "immer"479480const state = {481 hello: "world"482}483484produce(state, draft => {})485produce(state, draft => undefined)486// Both return the original state: { hello: "world"}487488produce(state, draft => nothing)489// Produces a new state, 'undefined'490```491492N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.493494## Inline shortcuts using `void`495496Draft 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.497498In 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`.499500```javascript501// Single mutation502produce(draft => void (draft.user.age += 1))503504// Multiple mutations505produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))506```507508Code 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.509510## Extracting the original object from a proxied instance511512Immer 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.513514```js515import {original} from "immer"516517const baseState = {users: [{name: "Richie"}]}518const nextState = produce(baseState, draftState => {519 original(draftState.users) // is === baseState.users520})521```522523Just want to know if a value is a proxied instance? Use the `isDraft` function!524525```js526import {isDraft} from "immer"527528const baseState = {users: [{name: "Bobby"}]}529const nextState = produce(baseState, draft => {530 isDraft(draft) // => true531 isDraft(draft.users) // => true532 isDraft(draft.users[0]) // => true533})534isDraft(nextState) // => false535```536537## Auto freezing538539Immer 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.540541_⚠️ 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! ⚠️_542543## Immer on older JavaScript environments?544545By 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.546547## Importing immer548549`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:550551```javascript552import produce from "immer"553import {produce} from "immer"554555const {produce} = require("immer")556const produce = require("immer").produce557const produce = require("immer").default558559import unleashTheMagic from "immer"560import {produce as unleashTheMagic} from "immer"561```562563## Supported object types564565Plain objects and arrays are always drafted by Immer.566567Every 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.568569```js570import {immerable} from "immer"571572class Foo {573 [immerable] = true // Option 1574575 constructor() {576 this[immerable] = true // Option 2577 }578}579580Foo[immerable] = true // Option 3581```582583For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.584585When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.586587Built-in classes like `Map` and `Set` are not supported. As a workaround, you should clone them before mutating them in a producer:588589```js590const state = {591 set: new Set(),592 map: new Map()593}594const nextState = produce(state, draft => {595 // Don't use any Set methods, as that mutates the instance!596 draft.set.add("foo") // ❌597598 // 1. Instead, clone the set (just once)599 const newSet = new Set(draft.set) // ✅600601 // 2. Mutate the clone (just in this producer)602 newSet.add("foo")603604 // 3. Update the draft with the new set605 draft.set = newSet606607 // Similarly, don't use any Map methods.608 draft.map.set("foo", "bar") // ❌609610 // 1. Instead, clone the map (just once)611 const newMap = new Map(draft.map) // ✅612613 // 2. Mutate it614 newMap.set("foo", "bar")615616 // 3. Update the draft617 draft.map = newMap618})619```620621## TypeScript or Flow622623The 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.624625The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:626627```ts628import produce from "immer"629630interface State {631 readonly x: number632}633634// `x` cannot be modified here635const state: State = {636 x: 0637}638639const newState = produce(state, draft => {640 // `x` can be modified here641 draft.x++642})643644// `newState.x` cannot be modified here645```646647This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!648649For 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:650651```ts652import produce, {Draft} from "immer"653654interface State {655 readonly x: number656}657658// `x` cannot be modified here659const state: State = {660 x: 0661}662663const increment = produce((draft: Draft<State>, inc: number) => {664 // `x` can be modified here665 draft.x += inc666})667668const newState = increment(state, 2)669// `newState.x` cannot be modified here670```671672**Note:** Immer v1.9+ supports TypeScript v3.1+ only.673674**Note:** Immer v3.0+ supports TypeScript v3.4+ only.67526# Pitfalls27281. 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).291. 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.
72 unmodified lines
102 draft[draft.findIndex(todo => todo.id === "id1")].done = true103})104```105756## Performance757758Here 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.759760These tests were executed on Node 9.3.0. Use `yarn test:perf` to reproduce them locally.761762![performance.png](images/performance.png)763764Most important observation:765766- 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.770106## Migration107108**Immer 2.\* -> 3.0**109
10 unmodified lines
120When 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.121122## FAQ123789_(for those who skimmed the above instead of actually reading)_790791**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**792793A: Yes794795**Q: Does Immer support deep updates?**796797A: Yes798799**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**800801A: Yes802803**Q: Can I typecheck my data structures when using Immer?**804805A: Yes806807**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**808809A: Yes810811**Q: Is it fast?**812813A: Yes814815**Q: Idea! Can Immer freeze the state for me?**816817A: Yes818124## Credits125126Special thanks to @Mendix, which supports its employees to experiment completely freely two full days a month, which formed the kick-start for this project.127
3 unmodified lines
added:docs/example-reducer.md+48 added
added:docs/example-setstate.md+34 added
added:docs/faq.md+37 added
1---2id: faq3title: Frequently Asked Questions4sidebar_label: FAQ5---67<div id="codefund"><!-- fallback content --></div>89_For those who skimmed the documentation instead of actually reading_1011**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**1213A: Yes1415**Q: Does Immer support deep updates?**1617A: Yes1819**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**2021A: Yes2223**Q: Can I typecheck my data structures when using Immer?**2425A: Yes2627**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**2829A: Yes3031**Q: Is it fast?**3233A: Yes3435**Q: Idea! Can Immer freeze the state for me?**3637A: Yes
added:docs/freezing.md+8 added
1---2id: freezing3title: Auto freezing4---56Immer 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.78_⚠️ 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! ⚠️_
added:docs/installation.md+34 added
1---2id: installation3title: Installation4---56<div id="codefund"><!-- fallback content --></div>78Immer can be installed as a direct dependency, and will work in any ES5 environment:910- Yarn: `yarn add immer`11- NPM: `npm install immer`12- CDN: Exposed global is `immer`13 - Unpkg: `<script src="https://unpkg.com/immer/dist/immer.umd.js"></script>`14 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js"></script>`1516## Importing immer1718`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:1920```javascript21import produce from "immer"22import {produce} from "immer"2324const {produce} = require("immer")25const produce = require("immer").produce26const produce = require("immer").default2728import unleashTheMagic from "immer"29import {produce as unleashTheMagic} from "immer"30```3132## Immer on older JavaScript environments?3334By 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 (if < v0.59 or when using the Hermes engine) on Android. In such cases, Immer will fallback to an ES5 compatible implementation which works identical, but is a bit slower.
added:docs/introduction.md+65 added
1---2id: introduction3title: Introduction to Immer4sidebar_label: Introduction5---67<div id="codefund"><!-- fallback content --></div>89<img src="/immer/img/immer-logo.png" height="200px" align="right"/>1011# Immer1213Winner of the "Breakthrough of the year" [React open source award](https://osawards.com/react/) and "Most impactful contribution" [JavaScript open source award](https://osawards.com/javascript/) in 2019.1415- 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)1718---1920Immer (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.2122The 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.2324![immer-hd.png](/immer/img/immer.png)2526Using 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).2728A 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.2930## Example3132```javascript33import produce from "immer"3435const baseState = [36 {37 todo: "Learn typescript",38 done: true39 },40 {41 todo: "Try immer",42 done: false43 }44]4546const nextState = produce(baseState, draftState => {47 draftState.push({todo: "Tweet about it"})48 draftState[1].done = true49})50```5152The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.5354Head to the [next section](produce) to further dive into `produce`.5556## Benefits5758- Immutability with normal JavaScript objects and arrays. No new APIs to learn!59- Strongly typed, no string based paths selectors etc.60- Structural sharing out of the box61- Object freezing out of the box62- Deep updates are a breeze63- Boilerplate reduction. Less noise, more concise code.64- First class support for patches65- Small [![size](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js?compression=gzip)](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)
added:docs/original.md+32 added
1---2id: original3title: Extracting the original object from a proxied instance4sidebar_label: Original5---67<div id="codefund"><!-- fallback content --></div>89Immer 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.1011```js12import {original} from "immer"1314const baseState = {users: [{name: "Richie"}]}15const nextState = produce(baseState, draftState => {16 original(draftState.users) // is === baseState.users17})18```1920Just want to know if a value is a proxied instance? Use the `isDraft` function!2122```js23import {isDraft} from "immer"2425const baseState = {users: [{name: "Bobby"}]}26const nextState = produce(baseState, draft => {27 isDraft(draft) // => true28 isDraft(draft.users) // => true29 isDraft(draft.users[0]) // => true30})31isDraft(nextState) // => false32```
added:docs/patches.md+132 added
1---2id: patches3title: Patches4---56<div id="codefund"><!-- fallback content --></div>78During 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.910Patches are useful in few scenarios:1112- To exchange incremental updates with other parties, for example over websockets13- For debugging / traces, to see precisely how state is changed over time14- As basis for undo/redo or as an approach to replay changes on a slightly different state tree1516To 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:1718```javascript19import produce, {applyPatches} from "immer"2021let state = {22 name: "Micheal",23 age: 3224}2526// Let's assume the user is in a wizard, and we don't know whether27// his changes should end up in the base state ultimately or not...28let fork = state29// all the changes the user made in the wizard30let changes = []31// the inverse of all the changes made in the wizard32let inverseChanges = []3334fork = produce(35 fork,36 draft => {37 draft.age = 3338 },39 // The third argument to produce is a callback to which the patches will be fed40 (patches, inversePatches) => {41 changes.push(...patches)42 inverseChanges.push(...inversePatches)43 }44)4546// In the meantime, our original state is replaced, as, for example,47// some changes were received from the server48state = produce(state, draft => {49 draft.name = "Michel"50})5152// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!53state = applyPatches(state, changes)5455// state now contains the changes from both code paths!56expect(state).toEqual({57 name: "Michel", // changed by the server58 age: 33 // changed by the wizard59})6061// Finally, even after finishing the wizard, the user might change his mind and undo his changes...62state = applyPatches(state, inverseChanges)63expect(state).toEqual({64 name: "Michel", // Not reverted65 age: 32 // Reverted66})67```6869The 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:7071```json72[73 {74 "op": "replace",75 "path": ["profile"],76 "value": {"name": "Veria", "age": 5}77 },78 {"op": "remove", "path": ["tags", 3]}79]80```8182```json83[84 {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},85 {"op": "add", "path": ["tags", 3], "value": "kiddo"}86]87```8889### `produceWithPatches`9091Instead 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.9293```javascript94import {produceWithPatches} from "immer"9596const [nextState, patches, inversePatches] = produceWithPatches(97 {98 age: 3399 },100 draft => {101 draft.age++102 }103)104```105106Which produces:107108```javascript109;[110 {111 age: 34112 },113 [114 {115 op: "replace",116 path: ["age"],117 value: 34118 }119 ],120 [121 {122 op: "replace",123 path: ["age"],124 value: 33125 }126 ]127]128```129130For 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)131132Tip: Check this trick to [compress patches](https://medium.com/@david.b.edelstein/using-immer-to-compress-immer-patches-f382835b6c69) produced over time.
added:docs/performance.md+21 added
1---2id: performance3title: Immer performance4---56<div id="codefund"><!-- fallback content --></div>78Here 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.910Something that isn't reflected in the numbers above, but in reality, Immer is sometimes significantly _faster_ than a hand written reducer. The reason for that is that Immer will detect "no-op" state changes, and return the original state if nothing actually changed, which can avoid a lot of re-renderings for example. Cases are known where simply applying immer solved critical performance issues.1112These tests were executed on Node 10.15.1. Use `yarn test:perf` to reproduce them locally.1314![performance.png](images/performance.png)1516Most important observation:1718- 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.19- 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)20- Generating patches doesn't significantly slow immer down21- The ES5 fallback implementation is roughly twice as slow as the proxy implementation, in some cases worse.
added:docs/pitfalls.md+6 added
1---2id: pitfalls3title: Pitfalls4---56<div id="codefund"><!-- fallback content --></div>
added:docs/produce.md+52 added
1---2id: produce3title: Using produce4---56<div id="codefund"><!-- fallback content --></div>78The Immer package exposes a default function that does all the work.910`produce(currentState, producer: (draftState) => void): nextState`1112There is also a curried overload that is explained [in a later section](curried-produce).1314## Example1516```javascript17import produce from "immer"1819const baseState = [20 {21 todo: "Learn typescript",22 done: true23 },24 {25 todo: "Try immer",26 done: false27 }28]2930const nextState = produce(baseState, draftState => {31 draftState.push({todo: "Tweet about it"})32 draftState[1].done = true33})34```3536The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.3738```javascript39// the new item is only added to the next state,40// base state is unmodified41expect(baseState.length).toBe(2)42expect(nextState.length).toBe(3)4344// same for the changed 'done' prop45expect(baseState[1].done).toBe(false)46expect(nextState[1].done).toBe(true)4748// unchanged data is structurally shared49expect(nextState[0]).toBe(baseState[0])50// changed data not (dûh)51expect(nextState[1]).not.toBe(baseState[1])52```
added:docs/resources.md+6 added
1---2id: resources3title: External resources4---56<div id="codefund"><!-- fallback content --></div>
added:docs/return.md+103 added
1---2id: return3title: Returning new data from producers4---56<div id="codefund"><!-- fallback content --></div>78It 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`.910It 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:1112```javascript13const userReducer = produce((draft, action) => {14 switch (action.type) {15 case "renameUser":16 // OK: we modify the current state17 draft.users[action.payload.id].name = action.payload.name18 return draft // same as just 'return'19 case "loadUsers":20 // OK: we return an entirely new state21 return action.payload22 case "adduser-1":23 // NOT OK: This doesn't do change the draft nor return a new state!24 // It doesn't modify the draft (it just redeclares it)25 // In fact, this just doesn't do anything at all26 draft = {users: [...draft.users, action.payload]}27 return28 case "adduser-2":29 // NOT OK: modifying draft *and* returning a new state30 draft.userCount += 131 return {users: [...draft.users, action.payload]}32 case "adduser-3":33 // OK: returning a new state. But, unnecessary complex and expensive34 return {35 userCount: draft.userCount + 1,36 users: [...draft.users, action.payload]37 }38 case "adduser-4":39 // OK: the immer way40 draft.userCount += 141 draft.users.push(action.payload)42 return43 }44})45```4647_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._4849## Producing `undefined` using `nothing`5051So, 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`:5253```javascript54produce({}, draft => {55 // don't do anything56})57```5859Versus:6061```javascript62produce({}, draft => {63 // Try to return undefined from the producer64 return undefined65})66```6768The 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.6970However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:7172```javascript73import produce, {nothing} from "immer"7475const state = {76 hello: "world"77}7879produce(state, draft => {})80produce(state, draft => undefined)81// Both return the original state: { hello: "world"}8283produce(state, draft => nothing)84// Produces a new state, 'undefined'85```8687N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.8889## Inline shortcuts using `void`9091Draft 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.9293In 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`.9495```javascript96// Single mutation97produce(draft => void (draft.user.age += 1))9899// Multiple mutations100produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))101```102103Code 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.
added:docs/support.md+6 added
1---2id: support3title: Supporting immer4---56<div id="codefund"><!-- fallback content --></div>
added:docs/typescript.md+62 added
1---2id: typescript3title: Using TypeScript or Flow4sidebar_label: TypeScript / Flow5---67<div id="codefund"><!-- fallback content --></div>89The 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.1011The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:1213```ts14import produce from "immer"1516interface State {17 readonly x: number18}1920// `x` cannot be modified here21const state: State = {22 x: 023}2425const newState = produce(state, draft => {26 // `x` can be modified here27 draft.x++28})2930// `newState.x` cannot be modified here31```3233This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!3435For 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:3637```ts38import produce, {Draft} from "immer"3940interface State {41 readonly x: number42}4344// `x` cannot be modified here45const state: State = {46 x: 047}4849const increment = produce((draft: Draft<State>, inc: number) => {50 // `x` can be modified here51 draft.x += inc52})5354const newState = increment(state, 2)55// `newState.x` cannot be modified here56```5758**Note:** Immer v1.9+ supports TypeScript v3.1+ only.5960**Note:** Immer v3.0+ supports TypeScript v3.4+ only.6162**Note:** Flow support might be removed in future versions and we recommend TypeScript
deleted:images/hd/immer.pngbinary

A binary file, deleted.

deleted:images/hd/proxy.pngbinary

A binary file, deleted.

deleted:images/hd/tree.pngbinary

A binary file, deleted.

deleted:images/immer.pngbinary

A binary file, deleted.

deleted:images/performance.pngbinary

A binary file, deleted.

deleted:images/proxy.pngbinary

A binary file, deleted.

deleted:images/tree.pngbinary

A binary file, deleted.

deleted:website/blog/2016-03-11-blog-post.md-18 removed
1---2title: Blog Title3author: Blog Author4authorURL: http://twitter.com/5authorFBID: 1000029765210036---78Lorem 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.910<!--truncate-->1112Mauris 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.1314Nulla 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.1516Orci 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.1718Phasellus 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.
deleted:website/blog/2017-04-10-blog-post-two.md-18 removed
1---2title: New Blog Post3author: Blog Author4authorURL: http://twitter.com/5authorFBID: 1000029765210036---78Lorem 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.910<!--truncate-->1112Mauris 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.1314Nulla 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.1516Orci 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.1718Phasellus 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.
deleted:website/blog/2017-09-25-testing-rss.md-14 removed
1---2title: Adding RSS Support - RSS Truncation Test3author: Eric Nakagawa4authorURL: http://twitter.com/ericnakagawa5authorFBID: 6612771736---781234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890910This should be truncated.1112<!--truncate-->1314This line should never render in XML.
deleted:website/blog/2017-09-26-adding-rss.md-10 removed
1---2title: Adding RSS Support3author: Eric Nakagawa4authorURL: http://twitter.com/ericnakagawa5authorFBID: 6612771736---78This is a test post.910A whole bunch of other information.
deleted:website/blog/2017-10-24-new-version-1.0.0.md-8 removed
1---2title: New Version 1.0.03author: Eric Nakagawa4authorURL: http://twitter.com/ericnakagawa5authorFBID: 6612771736---78This blog post will test file name parsing issues when periods are present.
modified:website/i18n/en.json+68 added-4 removed
3 unmodified lines
4 "next": "Next",5 "previous": "Previous",6 "tagline": "Create the next immutable state by mutating the current one",7 "docs": {8 "api": {9 "title": "API overview"10 },11 "async": {12 "title": "Async producers & createDraft / finishDraft",13 "sidebar_label": "async / createDraft"14 },15 "built-with": {16 "title": "Built with Immer"17 },18 "complex-objects": {19 "title": "Working with classes"20 },21 "curried-produce": {22 "title": "Curried producers"23 },24 "doc1": {25 "title": "Latin-ish",26 "sidebar_label": "Example Page"27 },28 "example-reducer": {29 "title": "Example Reducer"30 },31 "example-setstate": {32 "title": "React setState example"33 },34 "faq": {35 "title": "Frequently Asked Questions",36 "sidebar_label": "FAQ"37 },38 "freezing": {39 "title": "Auto freezing"40 },41 "installation": {42 "title": "Installation"43 },44 "introduction": {45 "title": "Introduction to Immer",46 "sidebar_label": "Introduction"47 },48 "original": {49 "title": "Extracting the original object from a proxied instance",50 "sidebar_label": "Original"51 },52 "patches": {53 "title": "Patches"54 },55 "performance": {56 "title": "Immer performance"57 },58 "pitfalls": {59 "title": "Pitfalls"60 },61 "produce": {62 "title": "Using produce"63 },64 "resources": {65 "title": "External resources"66 },67 "return": {68 "title": "Returning new data from producers"69 },70 "support": {71 "title": "Supporting immer"72 },73 "typescript": {74 "title": "Using TypeScript or Flow",75 "sidebar_label": "TypeScript / Flow"76 }77 },78 "links": {79 "Docs": "Docs",15 "API": "API",80 "Help": "Help"81 },82 "categories": {19 "Docusaurus": "Docusaurus",20 "First Category": "First Category",21 "Second Category": "Second Category"83 "Basics": "Basics",84 "Advanced Features": "Advanced Features",85 "Reources": "Reources"86 }87 },88 "pages-strings": {89 "Help Translate|recruit community translators for your project": "Help Translate",
4 unmodified lines
deleted:website/pages/en/index.js-214 removed
1/**2 * Copyright (c) 2017-present, Facebook, Inc.3 *4 * This source code is licensed under the MIT license found in the5 * LICENSE file in the root directory of this source tree.6 */78const React = require("react")910const CompLibrary = require("../../core/CompLibrary.js")1112const MarkdownBlock = CompLibrary.MarkdownBlock /* Used to read markdown */13const Container = CompLibrary.Container14const GridBlock = CompLibrary.GridBlock1516class HomeSplash extends React.Component {17 render() {18 const {siteConfig, language = ""} = this.props19 const {baseUrl, docsUrl} = siteConfig20 const docsPart = `${docsUrl ? `${docsUrl}/` : ""}`21 const langPart = `${language ? `${language}/` : ""}`22 const docUrl = doc => `${baseUrl}${docsPart}${langPart}${doc}`2324 const SplashContainer = props => (25 <div className="homeContainer">26 <div className="homeSplashFade">27 <div className="wrapper homeWrapper">{props.children}</div>28 </div>29 </div>30 )3132 const Logo = props => (33 <div className="projectLogo">34 <img src={props.img_src} alt="Project Logo" />35 </div>36 )3738 const ProjectTitle = () => (39 <h2 className="projectTitle">40 {siteConfig.title}41 <small>{siteConfig.tagline}</small>42 </h2>43 )4445 const PromoSection = props => (46 <div className="section promoSection">47 <div className="promoRow">48 <div className="pluginRowBlock">{props.children}</div>49 </div>50 </div>51 )5253 const Button = props => (54 <div className="pluginWrapper buttonWrapper">55 <a className="button" href={props.href} target={props.target}>56 {props.children}57 </a>58 </div>59 )6061 return (62 <SplashContainer>63 <Logo img_src={`${baseUrl}img/undraw_monitor.svg`} />64 <div className="inner">65 <ProjectTitle siteConfig={siteConfig} />66 <PromoSection>67 <Button href="#try">Try It Out</Button>68 <Button href={docUrl("doc1.html")}>Example Link</Button>69 <Button href={docUrl("doc2.html")}>Example Link 2</Button>70 </PromoSection>71 </div>72 </SplashContainer>73 )74 }75}7677class Index extends React.Component {78 render() {79 const {config: siteConfig, language = ""} = this.props80 const {baseUrl} = siteConfig8182 const Block = props => (83 <Container84 padding={["bottom", "top"]}85 id={props.id}86 background={props.background}87 >88 <GridBlock89 align="center"90 contents={props.children}91 layout={props.layout}92 />93 </Container>94 )9596 const FeatureCallout = () => (97 <div98 className="productShowcaseSection paddingBottom"99 style={{textAlign: "center"}}100 >101 <h2>Feature Callout</h2>102 <MarkdownBlock>These are features of this project</MarkdownBlock>103 </div>104 )105106 const TryOut = () => (107 <Block id="try">108 {[109 {110 content:111 "To make your landing page more attractive, use illustrations! Check out " +112 "[**unDraw**](https://undraw.co/) which provides you with customizable illustrations which are free to use. " +113 "The illustrations you see on this page are from unDraw.",114 image: `${baseUrl}img/undraw_code_review.svg`,115 imageAlign: "left",116 title: "Wonderful SVG Illustrations"117 }118 ]}119 </Block>120 )121122 const Description = () => (123 <Block background="dark">124 {[125 {126 content:127 "This is another description of how this project is useful",128 image: `${baseUrl}img/undraw_note_list.svg`,129 imageAlign: "right",130 title: "Description"131 }132 ]}133 </Block>134 )135136 const LearnHow = () => (137 <Block background="light">138 {[139 {140 content:141 "Each new Docusaurus project has **randomly-generated** theme colors.",142 image: `${baseUrl}img/undraw_youtube_tutorial.svg`,143 imageAlign: "right",144 title: "Randomly Generated Theme Colors"145 }146 ]}147 </Block>148 )149150 const Features = () => (151 <Block layout="fourColumn">152 {[153 {154 content: "This is the content of my feature",155 image: `${baseUrl}img/undraw_react.svg`,156 imageAlign: "top",157 title: "Feature One"158 },159 {160 content: "The content of my second feature",161 image: `${baseUrl}img/undraw_operating_system.svg`,162 imageAlign: "top",163 title: "Feature Two"164 }165 ]}166 </Block>167 )168169 const Showcase = () => {170 if ((siteConfig.users || []).length === 0) {171 return null172 }173174 const showcase = siteConfig.users175 .filter(user => user.pinned)176 .map(user => (177 <a href={user.infoLink} key={user.infoLink}>178 <img src={user.image} alt={user.caption} title={user.caption} />179 </a>180 ))181182 const pageUrl = page => baseUrl + (language ? `${language}/` : "") + page183184 return (185 <div className="productShowcaseSection paddingBottom">186 <h2>Who is Using This?</h2>187 <p>This project is used by all these people</p>188 <div className="logos">{showcase}</div>189 <div className="more-users">190 <a className="button" href={pageUrl("users.html")}>191 More {siteConfig.title} Users192 </a>193 </div>194 </div>195 )196 }197198 return (199 <div>200 <HomeSplash siteConfig={siteConfig} language={language} />201 <div className="mainContainer">202 <Features />203 <FeatureCallout />204 <LearnHow />205 <TryOut />206 <Description />207 <Showcase />208 </div>209 </div>210 )211 }212}213214module.exports = Index
modified:website/static/css/custom.css+8 added
12 unmodified lines
13}1415@media only screen and (min-width: 1500px) {16}1718a {19 color: #c200c2;20}2122a:hover {23 text-decoration: underline;24}
modified:website/static/img/favicon.icobinary

A binary file, modified.

added:website/static/img/immer-logo.pngbinary

A binary file, added.

added:website/static/img/immer.pngbinary

A binary file, added.

added:website/static/img/performance.pngbinary

A binary file, added.

added:website/static/img/proxy.pngbinary

A binary file, added.

added:website/static/img/tree.pngbinary

A binary file, added.

added:website/static/index.html+15 added
1<!DOCTYPE html>2<html lang="en-US">3 <head>4 <meta charset="UTF-8" />5 <meta http-equiv="refresh" content="0; url=docs/introduction" />6 <script type="text/javascript">7 window.location.href = "docs/introduction"8 </script>9 <title>Immer</title>10 </head>11 <body>12 If you are not redirected automatically, follow this13 <a href="docs/introduction">link</a>.14 </body>15</html>
deleted:website/README.md-198 removed
1This website was created with [Docusaurus](https://docusaurus.io/).23# What's In This Document45- [Get Started in 5 Minutes](#get-started-in-5-minutes)6- [Directory Structure](#directory-structure)7- [Editing Content](#editing-content)8- [Adding Content](#adding-content)9- [Full Documentation](#full-documentation)1011# Get Started in 5 Minutes12131. Make sure all the dependencies for the website are installed:1415```sh16# Install dependencies17$ yarn18```19202. Run your dev server:2122```sh23# Start the site24$ yarn start25```2627## Directory Structure2829Your project file structure should look something like this3031```32my-docusaurus/33 docs/34 doc-1.md35 doc-2.md36 doc-3.md37 website/38 blog/39 2016-3-11-oldest-post.md40 2017-10-24-newest-post.md41 core/42 node_modules/43 pages/44 static/45 css/46 img/47 package.json48 sidebar.json49 siteConfig.js50```5152# Editing Content5354## Editing an existing docs page5556Edit docs by navigating to `docs/` and editing the corresponding document:5758`docs/doc-to-be-edited.md`5960```markdown61---62id: page-needs-edit63title: This Doc Needs To Be Edited64---6566Edit me...67```6869For more information about docs, click [here](https://docusaurus.io/docs/en/navigation)7071## Editing an existing blog post7273Edit blog posts by navigating to `website/blog` and editing the corresponding post:7475`website/blog/post-to-be-edited.md`7677```markdown78---79id: post-needs-edit80title: This Blog Post Needs To Be Edited81---8283Edit me...84```8586For more information about blog posts, click [here](https://docusaurus.io/docs/en/adding-blog)8788# Adding Content8990## Adding a new docs page to an existing sidebar91921. Create the doc as a new markdown file in `/docs`, example `docs/newly-created-doc.md`:9394```md95---96id: newly-created-doc97title: This Doc Needs To Be Edited98---99100My new content here..101```1021031. Refer to that doc's ID in an existing sidebar in `website/sidebar.json`:104105```javascript106// Add newly-created-doc to the Getting Started category of docs107{108 "docs": {109 "Getting Started": [110 "quick-start",111 "newly-created-doc" // new doc here112 ],113 ...114 },115 ...116}117```118119For more information about adding new docs, click [here](https://docusaurus.io/docs/en/navigation)120121## Adding a new blog post1221231. Make sure there is a header link to your blog in `website/siteConfig.js`:124125`website/siteConfig.js`126127```javascript128headerLinks: [129 ...130 { blog: true, label: 'Blog' },131 ...132]133```1341352. Create the blog post with the format `YYYY-MM-DD-My-Blog-Post-Title.md` in `website/blog`:136137`website/blog/2018-05-21-New-Blog-Post.md`138139```markdown140---141author: Frank Li142authorURL: https://twitter.com/foobarbaz143authorFBID: 503283835144title: New Blog Post145---146147Lorem Ipsum...148```149150For more information about blog posts, click [here](https://docusaurus.io/docs/en/adding-blog)151152## Adding items to your site's top navigation bar1531541. Add links to docs, custom pages or external links by editing the headerLinks field of `website/siteConfig.js`:155156`website/siteConfig.js`157158```javascript159{160 headerLinks: [161 ...162 /* you can add docs */163 { doc: 'my-examples', label: 'Examples' },164 /* you can add custom pages */165 { page: 'help', label: 'Help' },166 /* you can add external links */167 { href: 'https://github.com/facebook/Docusaurus', label: 'GitHub' },168 ...169 ],170 ...171}172```173174For more information about the navigation bar, click [here](https://docusaurus.io/docs/en/navigation)175176## Adding custom pages1771781. Docusaurus uses React components to build pages. The components are saved as .js files in `website/pages/en`:1791. If you want your page to show up in your navigation header, you will need to update `website/siteConfig.js` to add to the `headerLinks` element:180181`website/siteConfig.js`182183```javascript184{185 headerLinks: [186 ...187 { page: 'my-new-custom-page', label: 'My New Custom Page' },188 ...189 ],190 ...191}192```193194For more information about custom pages, click [here](https://docusaurus.io/docs/en/custom-pages).195196# Full Documentation197198Full documentation can be found on the [website](https://docusaurus.io/).
modified:website/sidebars.json+4 added-7 removed
1{2 "docs": {3 "Docusaurus": ["doc1"],4 "First Category": ["doc2"],5 "Second Category": ["doc3"]6 },7 "docs-other": {8 "First Category": ["doc4", "doc5"]2 "Immer": {3 "Basics": ["introduction", "installation", "produce", "curried-produce", "api", "example-reducer", "example-setstate"],4 "Advanced Features": ["return", "patches", "freezing", "original", "async", "complex-objects"],5 "Reources": ["resources", "faq", "pitfalls", "built-with", "sponsor"]6 }7}
modified:website/siteConfig.js+7 added-1 removed
11 unmodified lines
12 title: "Immer", // Title for your website.13 tagline: "Create the next immutable state by mutating the current one",14 url: "https://immerjs.github.io", // Your website URL15 baseUrl: "/immer/", // Base URL for your project */16 editUrl: "https://github.com/immerjs/immer/edit/master/docs/",17 noIndex: true,18 // For github.io type URLs, you would set the url and baseUrl like:19 // url: 'https://facebook.github.io',20 // baseUrl: '/test-site/',2122 // Used for publishing and more23 projectName: "immer",24 organizationName: "immerjs",25 gaTrackingId: "UA-65632006-3",26 // For top-level user or org sites, the organization is still the same.27 // e.g., for the https://JoelMarcey.github.io site, it would be set like...28 // organizationName: 'JoelMarcey'29
33 unmodified lines
63 theme: "dracula"64 },6566 // Add custom scripts here that would be placed in <script> tags.64 scripts: ["https://buttons.github.io/buttons.js"],67 scripts: [68 "https://buttons.github.io/buttons.js",69 "https://codefund.io/properties/439/funder.js"70 ],7172 // On page navigation for the current documentation page.73 onPageNav: "separate",74 // No .html extensions for paths.
22 unmodified lines
modified:.gitignore+1 added
57 unmodified lines
58.env5960.idea61dist/62website/build
modified:package.json+2 added-1 removed
16 unmodified lines
17 "test:dts": "tsc -p __tests__/tsconfig.json --noEmit",18 "watch": "jest --watch",19 "coveralls": "jest --coverage && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls && rm -rf ./coverage",20 "build": "rimraf dist/ && yarn-or-npm bili && yarn-or-npm typed",21 "typed": "cpx 'src/immer.{d.ts,js.flow}' dist -v"21 "typed": "cpx 'src/immer.{d.ts,js.flow}' dist -v",22 "publish-docs": "cd website && GIT_USER=mweststrate USE_SSH=true yarn run publish-gh-pages"23 },24 "husky": {25 "hooks": {26 "pre-commit": "pretty-quick --staged"
61 unmodified lines