Skip to content
Myr

Some dots

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 198e05f · Browse files · 16 files+308 added−72 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

16 files+308 added−72 removed

  • tests:+120 added−0 removed
  • other:+188 added−72 removed

16 files+308 added−72 removed

modified:__tests__/base.js+93 added
2237 unmodified lines
2238 expect(state._bar).toEqual(0)2239 expect(state.bar).toEqual(0)2240 })2241 })22422243 describe("setter only", () => {2244 let setterCalled = 02245 class State {2246 [immerable] = true2247 x = 02248 set y(value) {2249 setterCalled++2250 this.x = value2251 }2252 }22532254 const state = new State()2255 const next = produce(state, draft => {2256 expect(draft.y).toBeUndefined()2257 draft.y = 2 // setter is inherited, so works2258 expect(draft.x).toBe(2)2259 })2260 expect(setterCalled).toBe(1)2261 expect(next.x).toBe(2)2262 expect(state.x).toBe(0)2263 })22642265 describe("getter only", () => {2266 let getterCalled = 02267 class State {2268 [immerable] = true2269 x = 02270 get y() {2271 getterCalled++2272 return this.x2273 }2274 }22752276 const state = new State()2277 const next = produce(state, draft => {2278 expect(draft.y).toBe(0)2279 expect(() => {2280 draft.y = 22281 }).toThrow("Cannot set property y")2282 draft.x = 22283 expect(draft.y).toBe(2)2284 })2285 expect(next.x).toBe(2)2286 expect(next.y).toBe(2)2287 expect(state.x).toBe(0)2288 })22892290 describe("own setter only", () => {2291 let setterCalled = 02292 const state = {2293 x: 0,2294 set y(value) {2295 setterCalled++2296 this.x = value2297 }2298 }22992300 const next = produce(state, draft => {2301 expect(draft.y).toBeUndefined()2302 // setter is not preserved, so we can write2303 draft.y = 22304 expect(draft.x).toBe(0)2305 expect(draft.y).toBe(2)2306 })2307 expect(setterCalled).toBe(0)2308 expect(next.x).toBe(0)2309 expect(next.y).toBe(2)2310 expect(state.x).toBe(0)2311 })23122313 describe("own getter only", () => {2314 let getterCalled = 02315 const state = {2316 x: 0,2317 get y() {2318 getterCalled++2319 return this.x2320 }2321 }23222323 const next = produce(state, draft => {2324 expect(draft.y).toBe(0)2325 // de-referenced, so stores it locally2326 draft.y = 22327 expect(draft.y).toBe(2)2328 expect(draft.x).toBe(0)2329 })2330 expect(getterCalled).not.toBe(1)2331 expect(next.x).toBe(0)2332 expect(next.y).toBe(2)2333 expect(state.x).toBe(0)2334 })2335}23362337function testLiteralTypes(produce) {2338 class Foo {}
68 unmodified lines
modified:__tests__/readme.js+27 added
232 unmodified lines
233 expect(usersById_v1.size).toBe(0)234 // And trying to change a Map outside a producers is going to: NO!235 expect(() => usersById_v3.clear()).toThrowErrorMatchingSnapshot()236})237238test("clock class", () => {239 class Clock {240 [immerable] = true241242 constructor(hour, minute) {243 this.hour = hour244 this.minute = minute245 }246247 get time() {248 return `${this.hour}:${this.minute}`249 }250251 tick() {252 return produce(this, draft => {253 draft.minute++254 })255 }256 }257258 const clock1 = new Clock(12, 10)259 const clock2 = clock1.tick()260 expect(clock1.time).toEqual("12:10") // 12:10261 expect(clock2.time).toEqual("12:11") // 12:11262 expect(clock2).toBeInstanceOf(Clock)263})
modified:docs/api.md+1 added
modified:docs/complex-objects.md+47 added-54 removed
added:docs/current.md+56 added
modified:docs/freezing.md+2 added
modified:docs/installation.md+7 added-7 removed
10 unmodified lines
11- NPM: `npm install immer`12- CDN: Exposed global is `immer`13 - Unpkg: `<script src="https://unpkg.com/immer"></script>`14 - JSDelivr: `<script src="https://cdn.jsdelivr.net/npm/immer"></script>`15 - ⚠️ When using a CDN, it is best to check the url in your browser and see what version it resolves to, so that your users aren't accidentally served a newer version in the future when updates are release. So use an url like: https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js instead. Substitute `production.min` with `development` in the URL for a development build. 15 - ⚠️ When using a CDN, it is best to check the url in your browser and see what version it resolves to, so that your users aren't accidentally served a newer version in the future when updates are release. So use an url like: https://unpkg.com/immer@6.0.3/dist/immer.umd.production.min.js instead. Substitute `production.min` with `development` in the URL for a development build.1617## Pick your Immer version1819_This section only applies to version 6 and later_
38 unmodified lines
58Import size report for immer:59┌───────────────────────┬───────────┬────────────┬───────────┐60│ (index) │ just this │ cumulative │ increment │61├───────────────────────┼───────────┼────────────┼───────────┤62│ import * from 'immer' │ 5606 │ 0 │ 0 │63│ produce │ 3085 │ 3085 │ 0 │64│ enableES5 │ 3870 │ 3878 │ 793 │65│ enableMapSet │ 3893 │ 4654 │ 776 │66│ enablePatches │ 3826 │ 5387 │ 733 │67│ enableAllPlugins │ 5382 │ 5421 │ 34 │62│ import * from 'immer' │ 5662 │ 0 │ 0 │63│ produce │ 3100 │ 3100 │ 0 │64│ enableES5 │ 3761 │ 3770 │ 670 │65│ enableMapSet │ 3885 │ 4527 │ 757 │66│ enablePatches │ 3891 │ 5301 │ 774 │67│ enableAllPlugins │ 5297 │ 5348 │ 47 │68└───────────────────────┴───────────┴────────────┴───────────┘69(this report was generated by npmjs.com/package/import-size)70```71
5 unmodified lines
added:docs/map-set.md+58 added
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_
modified:docs/original.md+2 added-2 removed
1---2id: original3title: Extracting the original object from a proxied instance3title: Extracting the original state from a draft4sidebar_label: Original5---67<div id="codefund"><!-- fallback content --></div>
8 unmodified lines
16 original(draftState.users) // is === baseState.users17})18```1920Just want to know if a value is a proxied instance? Use the `isDraft` function!20Just want to know if a value is a proxied instance? Use the `isDraft` function! Note that `original` cannot be invoked on objects that aren't drafts.2122```js23import {isDraft, produce} from "immer"24
8 unmodified lines
modified:docs/pitfalls.md+1 added
10 unmodified lines
111. 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. Also note that `original` can be used to get the original state of an object, which is cheaper to read.121. It is possible to return values from producers, except, it is not possible to return `undefined` that way, as it is indistinguishable from not updating the draft at all! If you want to replace the draft with `undefined`, just return `nothing` from the producer.131. Immer [does not support exotic objects](https://github.com/immerjs/immer/issues/504) such as window.location.141. You will need to enable your own classes to work properly with Immer. For docs on the topic, check out the section on [working with complex objects](https://immerjs.github.io/immer/docs/complex-objects).151. For arrays, only numeric properties and the `length` property can be mutated. Custom properties are not preserved on arrays.161. Note that data that comes from the closure, and not from the base state, will never be drafted, even when the data has become part of the new draft:1718```javascript19function onReceiveTodo(todo) {
13 unmodified lines
modified:src/core/current.ts+1 added
41 unmodified lines
42 each(copy, (key, childValue) => {43 if (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change44 set(copy, key, currentImpl(childValue))45 })46 // In the future, we might consider freezing here, based on the current settings47 return archType === ArchtypeSet ? new Set(copy) : copy48}4950function copyHelper(value: any, archType: number): any {
10 unmodified lines
modified:src/plugins/es5.ts-2 removed
43 unmodified lines
44 }4546 function createES5Draft(isArray: boolean, base: any) {47 // Create a new object / array, where each own property is trapped with an accessor48 // TODO: extract all utils used in this fn?48 const descriptors = Object.getOwnPropertyDescriptors(base)49 // Descriptors we want to skip:50 if (isArray) delete descriptors.length51 delete descriptors[DRAFT_STATE as any]
19 unmodified lines
71 const isArray = Array.isArray(base)72 const draft = createES5Draft(isArray, base)7374 const state: ES5ObjectState | ES5ArrayState = {76 // TODO: reuse this object construction from proxy?75 type_: isArray ? ProxyTypeES5Array : (ProxyTypeES5Object as any),76 scope_: parent ? parent.scope_ : getCurrentScope(),77 modified_: false,78 finalized_: false,
188 unmodified lines
modified:src/utils/common.ts+2 added-3 removed
153 unmodified lines
154 }155 // like object.assign, we will read any _own_, get/set accessors. This helps in dealing156 // with libraries that trap values, like mobx or vue157 // unlike object.assign, non-enumerables will be copied as well158 // TODO: document!159 if (desc.get)158 if (desc.get || desc.set)159 descriptors[key] = {160 configurable: true,162 writable: !!desc.set, // could live with 'true' as well here...161 writable: true, // could live with !!desc.set as well here...162 enumerable: desc.enumerable,163 value: base[key]164 }165 }
21 unmodified lines
modified:website/i18n/en.json+9 added-2 removed
14 unmodified lines
15 "built-with": {16 "title": "Built with Immer"17 },18 "complex-objects": {19 "title": "Working with Map, Set and classes"19 "title": "Classes"20 },21 "current": {22 "title": "Extracting the current state from a draft",23 "sidebar_label": "Current"24 },25 "curried-produce": {26 "title": "Curried producers"27 },28 "example-reducer": {
15 unmodified lines
44 "introduction": {45 "title": "Introduction to Immer",46 "sidebar_label": "Introduction"47 },48 "map-set": {49 "title": "Map and Set"50 },51 "original": {45 "title": "Extracting the original object from a proxied instance",52 "title": "Extracting the original state from a draft",53 "sidebar_label": "Original"54 },55 "patches": {56 "title": "Patches"
41 unmodified lines
modified:website/sidebars.json+1 added-1 removed
1{2 "Immer": {3 "Basics": ["introduction", "installation", "produce", "curried-produce", "example-reducer", "example-setstate"],4 "Advanced Features": ["api", "typescript", "return", "patches", "freezing", "original", "async", "complex-objects"],4 "Advanced Features": ["api", "map-set", "complex-objects", "current", "original", "patches", "freezing", "return", "async", "typescript"],5 "Resources": ["performance", "resources", "faq", "pitfalls", "built-with", "support"]6 }7}
modified:package.json+1 added-1 removed
1{2 "name": "immer",3 "version": "6.0.0-alpha.4",3 "version": "7.0.0-beta.0",4 "description": "Create your next immutable state by mutating the current one",5 "main": "dist/index.js",6 "module": "dist/immer.esm.js",7 "umd:main": "dist/immer.umd.production.min.js",
92 unmodified lines