complex-objects.md
This file
Path
docs/complex-objects.md
66 lines · 1.9 KiB · Markdown
Last changed by
docs: added Map exampleMichel Weststratebefore adoption85361a7
History of this fileTake it
Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 1–7why, one step back1---2id: complex-objects3title: Working with classes4---56<div id="codefund"><!-- fallback content --></div>7docs: added Map exampleMichel Weststratebefore adoption85361a7
lines 8–44why, one step back8Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer. An example of using Maps with immer:910```javascript11test("Producers can update Maps", () => {12 const usersById_v1 = new Map()1314 const usersById_v2 = produce(usersById_v1, draft => {15 // Modifying a map results in a new map16 draft.set("michel", {name: "Michel Weststrate", country: "NL"})17 })1819 const usersById_v3 = produce(usersById_v2, draft => {20 // Making a change deep inside a map, results in a new map as well!21 draft.get("michel").country = "UK"22 })2324 expect(usersById_v2).not.toBe(usersById_v1)25 expect(usersById_v3).not.toBe(usersById_v2)26 expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)27 expect(usersById_v2).toMatchInlineSnapshot(`28 Map {29 "michel" => Object {30 "country": "NL",31 "name": "Michel Weststrate",32 },33 }34 `)35 expect(usersById_v3).toMatchInlineSnapshot(`36 Map {37 "michel" => Object {38 "country": "UK",39 "name": "Michel Weststrate",40 },41 }42 `)43})44```Merge pull request #421 from immerjs/docsMichel Weststratebefore adoption9be6e46
lines 45–65why, one step back4546Every 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.4748```js49import {immerable} from "immer"5051class Foo {52 [immerable] = true // Option 15354 constructor() {55 this[immerable] = true // Option 256 }57}5859Foo[immerable] = true // Option 360```6162For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.6364When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.65feat: added first class support for `Map` and `Set`Michel Weststratebefore adoptionb6f1d40
line 66why, one step back66Maps and Sets that are produced by Immer will be made artificially immutable. This means that they will throw an exception when trying mutative methods like `set`, `clear` etc. outside a producer.