complex-objects.md
This file
Path
docs/complex-objects.md
62 lines · 1.6 KiB · Markdown
Last changed by
Merge branch 'master' into v4Michel Weststratebefore adoption741e941
History of this fileTake it
Merge branch 'master' into v4Michel Weststratebefore adoption741e941
lines 1–62why, one step back1---2id: complex-objects3title: Working with classes4---56<div id="codefund"><!-- fallback content --></div>78Plain objects and arrays are always drafted by Immer.910Every 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.1112```js13import {immerable} from "immer"1415class Foo {16 [immerable] = true // Option 11718 constructor() {19 this[immerable] = true // Option 220 }21}2223Foo[immerable] = true // Option 324```2526For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.2728When working with `Date` objects, you should always create a new `Date` instance instead of mutating an existing `Date` object.2930Built-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:3132```js33const state = {34 set: new Set(),35 map: new Map()36}37const nextState = produce(state, draft => {38 // Don't use any Set methods, as that mutates the instance!39 draft.set.add("foo") // ❌4041 // 1. Instead, clone the set (just once)42 const newSet = new Set(draft.set) // ✅4344 // 2. Mutate the clone (just in this producer)45 newSet.add("foo")4647 // 3. Update the draft with the new set48 draft.set = newSet4950 // Similarly, don't use any Map methods.51 draft.map.set("foo", "bar") // ❌5253 // 1. Instead, clone the map (just once)54 const newMap = new Map(draft.map) // ✅5556 // 2. Mutate it57 newMap.set("foo", "bar")5859 // 3. Update the draft60 draft.map = newMap61})62```