Skip to content
Myr

map-set.md

This file

Path

website/docs/map-set.md

60 lines · 2.0 KiB · Markdown

Last changed by

chore: docusaurus upgradeMichel Weststratebefore adoption48a91b3

History of this file

Take it

The walk stopped after 200 commits: lines older than 3f9a94e point at it.

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 1–6why, one step back
1---
2id: map-set3title: Map and Set4---56<center>

chore: docusaurus upgradeMichel Weststratebefore adoption48a91b3

line 7why, one step back
7<div data-ea-publisher="immerjs" data-ea-type="image" className="horizontal bordered"></div>

chore: let's test before publishMichel Weststratebefore adoption3f9a94e

lines 8–60why, one step back
8</center>
910_⚠ Since version 6 support for `Map`s and `Set`s has to be enabled explicitly by calling [`enableMapSet()`](./installation.mdx#pick-your-immer-version) once when starting your application._1112Plain objects, arrays, `Map`s and `Set`s are always drafted by Immer. An example of using Maps with immer:1314```javascript15test("Producers can update Maps", () => {16 const usersById_v1 = new Map()1718 const usersById_v2 = produce(usersById_v1, draft => {19 // Modifying a map results in a new map20 draft.set("michel", {name: "Michel Weststrate", country: "NL"})21 })2223 const usersById_v3 = produce(usersById_v2, draft => {24 // Making a change deep inside a map, results in a new map as well!25 draft.get("michel").country = "UK"26 })2728 // We got a new map each time!29 expect(usersById_v2).not.toBe(usersById_v1)30 expect(usersById_v3).not.toBe(usersById_v2)31 // With different content obviously32 expect(usersById_v1).toMatchInlineSnapshot(`Map {}`)33 expect(usersById_v2).toMatchInlineSnapshot(`34 Map {35 "michel" => Object {36 "country": "NL",37 "name": "Michel Weststrate",38 },39 }40 `)41 expect(usersById_v3).toMatchInlineSnapshot(`42 Map {43 "michel" => Object {44 "country": "UK",45 "name": "Michel Weststrate",46 },47 }48 `)49 // The old one was never modified50 expect(usersById_v1.size).toBe(0)51 // And trying to change a Map outside a producers is going to: NO!52 expect(() => usersById_v3.clear()).toThrowErrorMatchingInlineSnapshot(53 `"This object has been frozen and should not be mutated"`54 )55})56```5758Maps 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.5960_Note: The **keys** of a map are never drafted! This is done to avoid confusing semantics and keep keys always referentially equal_