Added some docs on how to use Immer together with Map or Set
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 737dfe5 · Browse files · 2 files·+95 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+95 added−2 removed
- tests:+50 added−0 removed
- other:+45 added−2 removed
Provenance
- Commit
d9b4d56- Tree
ce58d4d- Author
Michel Weststrate <mweststrate@gmail.com>- Committer
Michel Weststrate <mweststrate@gmail.com>- Parent
737dfe5
2 files changed+95 added−2 removed
modified:__tests__/readme.js+50 added
94 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814994 unmodified lines name: "Michel", age: 32 }) })
it("can update set", () => { const state = { title: "hello", tokenSet: new Set() }
const nextState = produce(state, draft => { draft.title = draft.title.toUpperCase() // let immer do it's job // don't use the operations onSet, as that mutates the instance! // draft.tokenSet.add("c1342")
// instead: clone the set (once!) const newSet = new Set(draft.tokenSet) // mutate it once newSet.add("c1342") // update the draft with the new set draft.tokenSet = newSet })
expect(state).toEqual({title: "hello", tokenSet: new Set()}) expect(nextState).toEqual({ title: "HELLO", tokenSet: new Set(["c1342"]) }) })
it("can deep udpate map", () => { const state = { users: new Map([["michel", {name: "miche"}]]) }
const nextState = produce(state, draft => { const newUsers = new Map(draft.users) // mutate the new map and set a _new_ user object // but leverage produce again to deeply update it's contents newUsers.set( "michel", produce(draft.users.get("michel"), draft => { draft.name = "michel" }) ) draft.users = newUsers })
expect(state).toEqual({users: new Map([["michel", {name: "miche"}]])}) expect(nextState).toEqual({ users: new Map([["michel", {name: "michel"}]]) }) })})modified:readme.md+45 added-2 removed
15 unmodified lines16 17 * 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)18 * Introduction blogpost: [Immer: Immutability the easy way](https://medium.com/@mweststrate/introducing-immer-immutability-the-easy-way-9d73d8f71cb3)19 * [Talk](https://www.youtube.com/watch?v=-gJbS7YjcSo) + [slides](http://immer.surge.sh/) on Immer at React Finland 2018 by Michel Weststrate20+* 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)21 22 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.23 24 The basic idea is that you will apply all your changes to a temporarily _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.393 unmodified lines418 419 ## Pitfalls420 421 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).421-1. Currently, Immer only supports plain objects and arrays. PRs are welcome for more language built-in types like `Map` and `Set`.422+1. Currently, Immer only supports plain objects and arrays.423+1. Class instances are not, and will not be supported. Read here more on why that would be a [confusing, conceptual mismatch]424 1. Immer only processes native arrays and plain objects (with a prototype of `null` or `Object`). Any other type of value will be treated verbatim! So if you modify a `Map` or `Buffer` (or whatever complex object from the draft state), the changes will be persisted. But, both in your new and old state! So, in such cases, make sure to always produce fresh instances if you want to keep your state truly immutable.425 1. For example, working with `Date` objects is no problem, just make sure you never modify them (by using methods like `setYear` on an existing instance). Instead, always create fresh `Date` instances. Which is probably what you were unconsciously doing already.424-1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`426+1. Since Immer uses proxies, reading huge amounts of data from state comes with an overhead (especially in the ES5 implementation). If this ever becomes an issue (measure before you optimize!), do the current state analysis before entering the producer function or read from the `currentState` rather than the `draftState`. Also realize that immer is opt-in everywhere, so it is perfectly fine to manually write super performance critical reducers, and use immer for all the normal ones.427 1. Some debuggers (at least Node 6 is known) have trouble debugging when Proxies are in play. Node 8 is known to work correctly.428 1. Always try to pull `produce` 'up', for example `for (let x of y) produce(base, d => d.push(x))` is exponentially slower then `produce(base, d => { for (let x of y) d.push(x)})`429+1. Immer does not support built in data-structures like `Map` and `Set`. However, it is fine to just immutably "update" them yourself but still leverage immer wherever possible:430 431+```javascript432+const state = {433+ title: "hello",434+ tokenSet: new Set()435+}436+437+const nextState = produce(state, draft => {438+ draft.title = draft.title.toUpperCase() // let immer do it's job439+ // don't use the operations onSet, as that mutates the instance!440+ // draft.tokenSet.add("c1342")441+442+ // instead: clone the set (once!)443+ const newSet = new Set(draft.tokenSet)444+ // mutate the clone (just in this producer)445+ newSet.add("c1342")446+ // update the draft with the new set447+ draft.tokenSet = newSet448+})449+```450+451+Or a deep update in maps (well, don't use maps for this use case, but as example):452+453+```javascript454+const state = {455+ users: new Map(["michel", { name: "miche" }])456+}457+458+const nextState = produce(state, draft => {459+ const newUsers = new Map(draft.users)460+ // mutate the new map and set a _new_ user object461+ // but leverage produce again to base the new user object on the original one462+ newUsers.set("michel", produce(draft.users.get("michel"), draft => {463+ draft.name = "michel"464+ }))465+ draft.users = newUsers466+})467+```468+469+470+471 ## Cool things built with immer472 473 * [react-copy-write](https://github.com/aweary/react-copy-write) _Immutable state with a mutable API_474 * [redux-starter-kit](https://github.com/markerikson/redux-starter-kit) _A simple set of tools to make using Redux easier_117 unmodified lines