current.md
This file
Path
docs/current.md
56 lines · 1.7 KiB · Markdown
Last changed by
Immer 7Michel Weststratebefore adoption467ea5d
History of this fileTake it
Immer 7Michel Weststratebefore adoption467ea5d
lines 1–56why, one step back1---2id: current3title: Extracting the current state from a draft4sidebar_label: Current5---67<div id="codefund"><!-- fallback content --></div>89Immer exposes a named export `current` that create a copy of the current state of the draft. This can be very useful for debugging purposes (as those objects won't be Proxy objects and not be logged as such). Also, references to `current` can be safely leaked from a produce function. Put differently, `current` provides a snapshot of the current state of a draft.1011Objects generated by `current` work similar to the objects created by produce itself.12131. Unmodified objects will be structurally shared with the original objects.141. If no changes are made to a draft, generally it holds that `original(draft) === current(draft)`, but this is not guaranteed.151. Future changes to the draft won't be reflected in the object produced by `current` (except for references to undraftable objects)161. Unlinke `produce` objects created by `current` will _not_ be frozen.1718Use `current` sparingly, it can be a potentially expensive operation, especially when using ES5.1920Note that `current` cannot be invoked on objects that aren't drafts.2122### Example2324The following example shows the effect of `current` (and `original`):2526```js27const base = {28 x: 029}3031const next = produce(base, draft => {32 draft.x++33 const orig = original(draft)34 const copy = current(draft)35 console.log(orig.x)36 console.log(copy.x)3738 setTimeout(() => {39 // this will execute after the produce has finised!40 console.log(orig.x)41 console.log(copy.x)42 }, 100)4344 draft.x++45 console.log(draft.x)46})47console.log(next.x)4849// This will print50// 0 (orig.x)51// 1 (copy.x)52// 2 (draft.x)53// 2 (next.x)54// 0 (after timeout, orig.x)55// 1 (after timeout, copy.x)56```