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
Provenance
- Commit
12298be- Tree
0387859- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
79ec197
48 files changed+949 added−1190 removed
added:docs/api.md+8 added
12345678---id: apititle: API overview---
<div id="codefund"><!-- fallback content --></div>
api / description / further explanationadded:docs/async.md+45 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445---id: asynctitle: Async producers & createDraft / finishDraftsidebar_label: async / createDraft---
<div id="codefund"><!-- fallback content --></div>
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:
```javascriptimport produce from "immer"
const user = { name: "michel", todos: []}
const loadedUser = await produce(user, async function(draft) { draft.todos = await (await window.fetch("http://host/" + draft.name)).json()})```
_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._
## `createDraft` and `finishDraft`
`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:
```javascriptimport {createDraft, finishDraft} from "immer"
const user = { name: "michel", todos: []}
const draft = createDraft(user)draft.todos = await (await window.fetch("http://host/" + draft.name)).json()const loadedUser = finishDraft(draft)```
Note: `finishDraft` takes a `patchListener` as second argument, which can be used to record the patches, similarly to `produce`.
_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._added:docs/built-with.md+6 added
123456---id: built-withtitle: Built with Immer---
<div id="codefund"><!-- fallback content --></div>added:docs/complex-objects.md+62 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162---id: complex-objectstitle: Working with classes---
<div id="codefund"><!-- fallback content --></div>
Plain objects and arrays are always drafted by Immer.
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.
```jsimport {immerable} from "immer"
class Foo { [immerable] = true // Option 1
constructor() { this[immerable] = true // Option 2 }}
Foo[immerable] = true // Option 3```
For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.
When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.
Built-in classes like `Map` and `Set` are not yet supported (they might be if there is popular demand). As a workaround, you should clone them before mutating them in a producer:
```jsconst state = { set: new Set(), map: new Map()}const nextState = produce(state, draft => { // Don't use any Set methods, as that mutates the instance! draft.set.add("foo") // ❌
// 1. Instead, clone the set (just once) const newSet = new Set(draft.set) // ✅
// 2. Mutate the clone (just in this producer) newSet.add("foo")
// 3. Update the draft with the new set draft.set = newSet
// Similarly, don't use any Map methods. draft.map.set("foo", "bar") // ❌
// 1. Instead, clone the map (just once) const newMap = new Map(draft.map) // ✅
// 2. Mutate it newMap.set("foo", "bar")
// 3. Update the draft draft.map = newMap})```added:docs/curried-produce.md+75 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475---id: curried-producetitle: Curried producers---
<div id="codefund"><!-- fallback content --></div>
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.
For example:
```javascript// mapper will be of signature (state, index) => stateconst mapper = produce((draft, index) => { draft.index = index})
// example usageconsole.dir([{}, {}, {}].map(mapper))//[{index: 0}, {index: 1}, {index: 2}])```
This mechanism can also nicely be leveraged to further simplify our example reducer:
```javascriptimport produce from "immer"
const byId = produce((draft, action) => { switch (action.type) { case RECEIVE_PRODUCTS: action.products.forEach(product => { draft[product.id] = product }) return }})```
Note that `state` is now factored out (the created reducer will accept a state, and invoke the bound producer with it).
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`:
```javascriptimport produce from "immer"
const byId = produce( (draft, action) => { switch (action.type) { case RECEIVE_PRODUCTS: action.products.forEach(product => { draft[product.id] = product }) return } }, { 1: {id: 1, name: "product-1"} })```
##### Fun with currying
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:
```javascriptimport produce from "immer"const spread = produce(Object.assign)
const base = {x: 1, y: 1}
console.log({...base, y: 1} === base) // falseconsole.log(spread(base, {y: 1}) === base) // true! base is recycled as no actual new value was producedconsole.log(spread(base, {y: 2}) === base)`` // false, produced a new object as it should```modified:docs/doc1.md+2 added-697 removed
2 unmodified lines3 title: Latin-ish4 sidebar_label: Example Page5 ---6 7+<div id="codefund"><!-- fallback content --></div>8+9 - 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>`14 15 ---16 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-18-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-17 ## External resources18 19 - 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 line22 - 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/)25 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-```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-85-## Benefits86-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-95-Read further to see all these benefits explained.96-97-## Reducer Example98-99-Here is a simple example of the difference that Immer could make in practice.100-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-26 # Pitfalls27 28 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).29 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.72 unmodified lines102 draft[draft.findIndex(todo => todo.id === "id1")].done = true103 })104 ```105 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-106 ## Migration107 108 **Immer 2.\* -> 3.0**109 10 unmodified lines120 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.121 122 ## FAQ123 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-124 ## Credits125 126 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.127 3 unmodified linesadded:docs/example-reducer.md+48 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748---id: example-reducertitle: Example Reducer---
<div id="codefund"><!-- fallback content --></div>
Here is a simple example of the difference that Immer could make in practice.
```javascript// Redux reducer// Shortened, based on: https://github.com/reactjs/redux/blob/master/examples/shopping-cart/src/reducers/products.jsconst byId = (state, action) => { switch (action.type) { case RECEIVE_PRODUCTS: return { ...state, ...action.products.reduce((obj, product) => { obj[product.id] = product return obj }, {}) } default: return state }}```
After using Immer, that simply becomes:
```javascriptimport produce from "immer"
const byId = produce((draft, action) => { switch (action.type) { case RECEIVE_PRODUCTS: action.products.forEach(product => { draft[product.id] = product }) }})```
Notice that it is not needed to handle the default case, a producer that doesn't do anything will simply return the original state.
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).
_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._added:docs/example-setstate.md+34 added
12345678910111213141516171819202122232425262728293031323334---id: example-setstatetitle: React setState example---
<div id="codefund"><!-- fallback content --></div>
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)):
```javascript/** * Classic React.setState with a deep merge */onBirthDayClick1 = () => { this.setState(prevState => ({ user: { ...prevState.user, age: prevState.user.age + 1 } }))}
/** * ...But, since setState accepts functions, * we can just create a curried producer and further simplify! */onBirthDayClick2 = () => { this.setState( produce(draft => { draft.user.age += 1 }) )}```added:docs/faq.md+37 added
1+---2+id: faq3+title: Frequently Asked Questions4+sidebar_label: FAQ5+---6+7+<div id="codefund"><!-- fallback content --></div>8+9+_For those who skimmed the documentation instead of actually reading_10+11+**Q: Does Immer use structural sharing? So that my selectors can be memoized and such?**12+13+A: Yes14+15+**Q: Does Immer support deep updates?**16+17+A: Yes18+19+**Q: I can't rely on Proxies being present on my target environments. Can I use Immer?**20+21+A: Yes22+23+**Q: Can I typecheck my data structures when using Immer?**24+25+A: Yes26+27+**Q: Can I store `Date` objects, functions etc in my state tree when using Immer?**28+29+A: Yes30+31+**Q: Is it fast?**32+33+A: Yes34+35+**Q: Idea! Can Immer freeze the state for me?**36+37+A: Yesadded:docs/freezing.md+8 added
1+---2+id: freezing3+title: Auto freezing4+---5+6+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.7+8+_⚠️ 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+---2+id: installation3+title: Installation4+---5+6+<div id="codefund"><!-- fallback content --></div>7+8+Immer can be installed as a direct dependency, and will work in any ES5 environment:9+10+- 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>`15+16+## Importing immer17+18+`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:19+20+```javascript21+import produce from "immer"22+import {produce} from "immer"23+24+const {produce} = require("immer")25+const produce = require("immer").produce26+const produce = require("immer").default27+28+import unleashTheMagic from "immer"29+import {produce as unleashTheMagic} from "immer"30+```31+32+## Immer on older JavaScript environments?33+34+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 (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+---2+id: introduction3+title: Introduction to Immer4+sidebar_label: Introduction5+---6+7+<div id="codefund"><!-- fallback content --></div>8+9+<img src="/immer/img/immer-logo.png" height="200px" align="right"/>10+11+# Immer12+13+Winner 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.14+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+18+---19+20+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.21+22+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.23+24+25+26+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).27+28+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.29+30+## Example31+32+```javascript33+import produce from "immer"34+35+const baseState = [36+ {37+ todo: "Learn typescript",38+ done: true39+ },40+ {41+ todo: "Try immer",42+ done: false43+ }44+]45+46+const nextState = produce(baseState, draftState => {47+ draftState.push({todo: "Tweet about it"})48+ draftState[1].done = true49+})50+```51+52+The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.53+54+Head to the [next section](produce) to further dive into `produce`.55+56+## Benefits57+58+- 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 [](http://img.badgesize.io/https://cdn.jsdelivr.net/npm/immer/dist/immer.umd.js)added:docs/original.md+32 added
1+---2+id: original3+title: Extracting the original object from a proxied instance4+sidebar_label: Original5+---6+7+<div id="codefund"><!-- fallback content --></div>8+9+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.10+11+```js12+import {original} from "immer"13+14+const baseState = {users: [{name: "Richie"}]}15+const nextState = produce(baseState, draftState => {16+ original(draftState.users) // is === baseState.users17+})18+```19+20+Just want to know if a value is a proxied instance? Use the `isDraft` function!21+22+```js23+import {isDraft} from "immer"24+25+const baseState = {users: [{name: "Bobby"}]}26+const nextState = produce(baseState, draft => {27+ isDraft(draft) // => true28+ isDraft(draft.users) // => true29+ isDraft(draft.users[0]) // => true30+})31+isDraft(nextState) // => false32+```added:docs/patches.md+132 added
1+---2+id: patches3+title: Patches4+---5+6+<div id="codefund"><!-- fallback content --></div>7+8+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.9+10+Patches are useful in few scenarios:11+12+- 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 tree15+16+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:17+18+```javascript19+import produce, {applyPatches} from "immer"20+21+let state = {22+ name: "Micheal",23+ age: 3224+}25+26+// 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...28+let fork = state29+// all the changes the user made in the wizard30+let changes = []31+// the inverse of all the changes made in the wizard32+let inverseChanges = []33+34+fork = 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+)45+46+// In the meantime, our original state is replaced, as, for example,47+// some changes were received from the server48+state = produce(state, draft => {49+ draft.name = "Michel"50+})51+52+// When the wizard finishes (successfully) we can replay the changes that were in the fork onto the *new* state!53+state = applyPatches(state, changes)54+55+// state now contains the changes from both code paths!56+expect(state).toEqual({57+ name: "Michel", // changed by the server58+ age: 33 // changed by the wizard59+})60+61+// Finally, even after finishing the wizard, the user might change his mind and undo his changes...62+state = applyPatches(state, inverseChanges)63+expect(state).toEqual({64+ name: "Michel", // Not reverted65+ age: 32 // Reverted66+})67+```68+69+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:70+71+```json72+[73+ {74+ "op": "replace",75+ "path": ["profile"],76+ "value": {"name": "Veria", "age": 5}77+ },78+ {"op": "remove", "path": ["tags", 3]}79+]80+```81+82+```json83+[84+ {"op": "replace", "path": ["profile"], "value": {"name": "Noa", "age": 6}},85+ {"op": "add", "path": ["tags", 3], "value": "kiddo"}86+]87+```88+89+### `produceWithPatches`90+91+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.92+93+```javascript94+import {produceWithPatches} from "immer"95+96+const [nextState, patches, inversePatches] = produceWithPatches(97+ {98+ age: 3399+ },100+ draft => {101+ draft.age++102+ }103+)104+```105+106+Which produces:107+108+```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+```129+130+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)131+132+Tip: 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+---2+id: performance3+title: Immer performance4+---5+6+<div id="codefund"><!-- fallback content --></div>7+8+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.9+10+Something 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.11+12+These tests were executed on Node 10.15.1. Use `yarn test:perf` to reproduce them locally.13+14+15+16+Most important observation:17+18+- 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+---2+id: pitfalls3+title: Pitfalls4+---5+6+<div id="codefund"><!-- fallback content --></div>added:docs/produce.md+52 added
1+---2+id: produce3+title: Using produce4+---5+6+<div id="codefund"><!-- fallback content --></div>7+8+The Immer package exposes a default function that does all the work.9+10+`produce(currentState, producer: (draftState) => void): nextState`11+12+There is also a curried overload that is explained [in a later section](curried-produce).13+14+## Example15+16+```javascript17+import produce from "immer"18+19+const baseState = [20+ {21+ todo: "Learn typescript",22+ done: true23+ },24+ {25+ todo: "Try immer",26+ done: false27+ }28+]29+30+const nextState = produce(baseState, draftState => {31+ draftState.push({todo: "Tweet about it"})32+ draftState[1].done = true33+})34+```35+36+The interesting thing about Immer is that the `baseState` will be untouched, but the `nextState` will reflect all changes made to `draftState`.37+38+```javascript39+// the new item is only added to the next state,40+// base state is unmodified41+expect(baseState.length).toBe(2)42+expect(nextState.length).toBe(3)43+44+// same for the changed 'done' prop45+expect(baseState[1].done).toBe(false)46+expect(nextState[1].done).toBe(true)47+48+// unchanged data is structurally shared49+expect(nextState[0]).toBe(baseState[0])50+// changed data not (dûh)51+expect(nextState[1]).not.toBe(baseState[1])52+```added:docs/resources.md+6 added
1+---2+id: resources3+title: External resources4+---5+6+<div id="codefund"><!-- fallback content --></div>added:docs/return.md+103 added
1+---2+id: return3+title: Returning new data from producers4+---5+6+<div id="codefund"><!-- fallback content --></div>7+8+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`.9+10+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:11+12+```javascript13+const 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+```46+47+_Note: It is not possible to return `undefined` this way, as it is indistinguishable from *not* updating the draft! Read on..._48+49+## Producing `undefined` using `nothing`50+51+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`:52+53+```javascript54+produce({}, draft => {55+ // don't do anything56+})57+```58+59+Versus:60+61+```javascript62+produce({}, draft => {63+ // Try to return undefined from the producer64+ return undefined65+})66+```67+68+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.69+70+However, to make it clear to Immer that you intentionally want to produce the value `undefined`, you can return the built-in token `nothing`:71+72+```javascript73+import produce, {nothing} from "immer"74+75+const state = {76+ hello: "world"77+}78+79+produce(state, draft => {})80+produce(state, draft => undefined)81+// Both return the original state: { hello: "world"}82+83+produce(state, draft => nothing)84+// Produces a new state, 'undefined'85+```86+87+N.B. Note that this problem is specific for the `undefined` value, any other value, including `null`, doesn't suffer from this issue.88+89+## Inline shortcuts using `void`90+91+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.92+93+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`.94+95+```javascript96+// Single mutation97+produce(draft => void (draft.user.age += 1))98+99+// Multiple mutations100+produce(draft => void ((draft.user.age += 1), (draft.user.height = 186)))101+```102+103+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.added:docs/support.md+6 added
1+---2+id: support3+title: Supporting immer4+---5+6+<div id="codefund"><!-- fallback content --></div>added:docs/typescript.md+62 added
1+---2+id: typescript3+title: Using TypeScript or Flow4+sidebar_label: TypeScript / Flow5+---6+7+<div id="codefund"><!-- fallback content --></div>8+9+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.10+11+The TypeScript typings automatically remove `readonly` modifiers from your draft types and return a value that matches your original type. See this practical example:12+13+```ts14+import produce from "immer"15+16+interface State {17+ readonly x: number18+}19+20+// `x` cannot be modified here21+const state: State = {22+ x: 023+}24+25+const newState = produce(state, draft => {26+ // `x` can be modified here27+ draft.x++28+})29+30+// `newState.x` cannot be modified here31+```32+33+This ensures that the only place you can modify your state is in your produce callbacks. It even works recursively and with `ReadonlyArray`s!34+35+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:36+37+```ts38+import produce, {Draft} from "immer"39+40+interface State {41+ readonly x: number42+}43+44+// `x` cannot be modified here45+const state: State = {46+ x: 047+}48+49+const increment = produce((draft: Draft<State>, inc: number) => {50+ // `x` can be modified here51+ draft.x += inc52+})53+54+const newState = increment(state, 2)55+// `newState.x` cannot be modified here56+```57+58+**Note:** Immer v1.9+ supports TypeScript v3.1+ only.59+60+**Note:** Immer v3.0+ supports TypeScript v3.4+ only.61+62+**Note:** Flow support might be removed in future versions and we recommend TypeScriptdeleted: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----2-title: Blog Title3-author: Blog Author4-authorURL: http://twitter.com/5-authorFBID: 1000029765210036----7-8-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.9-10-<!--truncate-->11-12-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.13-14-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.15-16-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.17-18-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.deleted:website/blog/2017-04-10-blog-post-two.md-18 removed
1----2-title: New Blog Post3-author: Blog Author4-authorURL: http://twitter.com/5-authorFBID: 1000029765210036----7-8-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.9-10-<!--truncate-->11-12-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.13-14-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.15-16-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.17-18-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.deleted:website/blog/2017-09-25-testing-rss.md-14 removed
1----2-title: Adding RSS Support - RSS Truncation Test3-author: Eric Nakagawa4-authorURL: http://twitter.com/ericnakagawa5-authorFBID: 6612771736----7-8-12345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678909-10-This should be truncated.11-12-<!--truncate-->13-14-This line should never render in XML.deleted:website/blog/2017-09-26-adding-rss.md-10 removed
1----2-title: Adding RSS Support3-author: Eric Nakagawa4-authorURL: http://twitter.com/ericnakagawa5-authorFBID: 6612771736----7-8-This is a test post.9-10-A whole bunch of other information.deleted:website/blog/2017-10-24-new-version-1.0.0.md-8 removed
1----2-title: New Version 1.0.03-author: Eric Nakagawa4-authorURL: http://twitter.com/ericnakagawa5-authorFBID: 6612771736----7-8-This blog post will test file name parsing issues when periods are present.modified:website/i18n/en.json+68 added-4 removed
3 unmodified lines4 "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 linesdeleted: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- */7-8-const React = require("react")9-10-const CompLibrary = require("../../core/CompLibrary.js")11-12-const MarkdownBlock = CompLibrary.MarkdownBlock /* Used to read markdown */13-const Container = CompLibrary.Container14-const GridBlock = CompLibrary.GridBlock15-16-class 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}`23-24- const SplashContainer = props => (25- <div className="homeContainer">26- <div className="homeSplashFade">27- <div className="wrapper homeWrapper">{props.children}</div>28- </div>29- </div>30- )31-32- const Logo = props => (33- <div className="projectLogo">34- <img src={props.img_src} alt="Project Logo" />35- </div>36- )37-38- const ProjectTitle = () => (39- <h2 className="projectTitle">40- {siteConfig.title}41- <small>{siteConfig.tagline}</small>42- </h2>43- )44-45- const PromoSection = props => (46- <div className="section promoSection">47- <div className="promoRow">48- <div className="pluginRowBlock">{props.children}</div>49- </div>50- </div>51- )52-53- 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- )60-61- 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-}76-77-class Index extends React.Component {78- render() {79- const {config: siteConfig, language = ""} = this.props80- const {baseUrl} = siteConfig81-82- 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- )95-96- 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- )105-106- 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- )121-122- 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- )135-136- 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- )149-150- 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- )168-169- const Showcase = () => {170- if ((siteConfig.users || []).length === 0) {171- return null172- }173-174- 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- ))181-182- const pageUrl = page => baseUrl + (language ? `${language}/` : "") + page183-184- 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- }197-198- 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-}213-214-module.exports = Indexmodified:website/static/css/custom.css+8 added
12 unmodified lines13 }14 15 @media only screen and (min-width: 1500px) {16 }17+18+a {19+ color: #c200c2;20+}21+22+a: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
1-This website was created with [Docusaurus](https://docusaurus.io/).2-3-# What's In This Document4-5-- [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)10-11-# Get Started in 5 Minutes12-13-1. Make sure all the dependencies for the website are installed:14-15-```sh16-# Install dependencies17-$ yarn18-```19-20-2. Run your dev server:21-22-```sh23-# Start the site24-$ yarn start25-```26-27-## Directory Structure28-29-Your project file structure should look something like this30-31-```32-my-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-```51-52-# Editing Content53-54-## Editing an existing docs page55-56-Edit docs by navigating to `docs/` and editing the corresponding document:57-58-`docs/doc-to-be-edited.md`59-60-```markdown61----62-id: page-needs-edit63-title: This Doc Needs To Be Edited64----65-66-Edit me...67-```68-69-For more information about docs, click [here](https://docusaurus.io/docs/en/navigation)70-71-## Editing an existing blog post72-73-Edit blog posts by navigating to `website/blog` and editing the corresponding post:74-75-`website/blog/post-to-be-edited.md`76-77-```markdown78----79-id: post-needs-edit80-title: This Blog Post Needs To Be Edited81----82-83-Edit me...84-```85-86-For more information about blog posts, click [here](https://docusaurus.io/docs/en/adding-blog)87-88-# Adding Content89-90-## Adding a new docs page to an existing sidebar91-92-1. Create the doc as a new markdown file in `/docs`, example `docs/newly-created-doc.md`:93-94-```md95----96-id: newly-created-doc97-title: This Doc Needs To Be Edited98----99-100-My new content here..101-```102-103-1. Refer to that doc's ID in an existing sidebar in `website/sidebar.json`:104-105-```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-```118-119-For more information about adding new docs, click [here](https://docusaurus.io/docs/en/navigation)120-121-## Adding a new blog post122-123-1. Make sure there is a header link to your blog in `website/siteConfig.js`:124-125-`website/siteConfig.js`126-127-```javascript128-headerLinks: [129- ...130- { blog: true, label: 'Blog' },131- ...132-]133-```134-135-2. Create the blog post with the format `YYYY-MM-DD-My-Blog-Post-Title.md` in `website/blog`:136-137-`website/blog/2018-05-21-New-Blog-Post.md`138-139-```markdown140----141-author: Frank Li142-authorURL: https://twitter.com/foobarbaz143-authorFBID: 503283835144-title: New Blog Post145----146-147-Lorem Ipsum...148-```149-150-For more information about blog posts, click [here](https://docusaurus.io/docs/en/adding-blog)151-152-## Adding items to your site's top navigation bar153-154-1. Add links to docs, custom pages or external links by editing the headerLinks field of `website/siteConfig.js`:155-156-`website/siteConfig.js`157-158-```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-```173-174-For more information about the navigation bar, click [here](https://docusaurus.io/docs/en/navigation)175-176-## Adding custom pages177-178-1. Docusaurus uses React components to build pages. The components are saved as .js files in `website/pages/en`:179-1. 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:180-181-`website/siteConfig.js`182-183-```javascript184-{185- headerLinks: [186- ...187- { page: 'my-new-custom-page', label: 'My New Custom Page' },188- ...189- ],190- ...191-}192-```193-194-For more information about custom pages, click [here](https://docusaurus.io/docs/en/custom-pages).195-196-# Full Documentation197-198-Full 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 lines12 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/',21 22 // 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 lines63 theme: "dracula"64 },65 66 // 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+ ],71 72 // On page navigation for the current documentation page.73 onPageNav: "separate",74 // No .html extensions for paths.22 unmodified linesmodified:.gitignore+1 added
57 unmodified lines58 .env59 60 .idea61 dist/62+website/buildmodified:package.json+2 added-1 removed
16 unmodified lines17 "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