Skip to content
Myr

map-set.md

This file

Path

docs/map-set.md

58 lines · 1.9 KiB · Markdown

Last changed by

Immer 7Michel Weststratebefore adoption467ea5d

History of this file

Take it

Immer 7Michel Weststratebefore adoption467ea5d

lines 1–58why, one step back
1---
2id: map-set3title: Map and Set4---56<div id="codefund"><!-- fallback content --></div>78_⚠ Since version 6 support for `Map`s and `Set`s has to be enabled explicitly by calling [`enableMapSet()`](installation#pick-your-immer-version) once when starting your application._910Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer. An example of using Maps with immer:1112```javascript13test("Producers can update Maps", () => {14 const usersById_v1 = new Map()1516 const usersById_v2 = produce(usersById_v1, draft => {17 // Modifying a map results in a new map18 draft.set("michel", {name: "Michel Weststrate", country: "NL"})19 })2021 const usersById_v3 = produce(usersById_v2, draft => {22 // Making a change deep inside a map, results in a new map as well!23 draft.get("michel").country = "UK"24 })2526 // We got a new map each time!27 expect(usersById_v2).not.toBe(usersById_v1)28 expect(usersById_v3).not.toBe(usersById_v2)29 // With different content obviously30 expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)31 expect(usersById_v2).toMatchInlineSnapshot(`32 Map {33 "michel" => Object {34 "country": "NL",35 "name": "Michel Weststrate",36 },37 }38 `)39 expect(usersById_v3).toMatchInlineSnapshot(`40 Map {41 "michel" => Object {42 "country": "UK",43 "name": "Michel Weststrate",44 },45 }46 `)47 // The old one was never modified48 expect(usersById_v1.size).toBe(0)49 // And trying to change a Map outside a producers is going to: NO!50 expect(() => usersById_v3.clear()).toThrowErrorMatchingInlineSnapshot(51 `"This object has been frozen and should not be mutated"`52 )53})54```5556Maps 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.5758_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_