Extracting the current state from a draft
Immer exposes a named export current
that creates 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.
Objects generated by current
work similar to the objects created by produce itself.
- Unmodified objects will be structurally shared with the original objects.
- If no changes are made to a draft, generally it holds that
original(draft) === current(draft)
, but this is not guaranteed. - Future changes to the draft won't be reflected in the object produced by
current
(except for references to undraftable objects) - Unlike
produce
objects created bycurrent
will not be frozen.
Use current
sparingly, it can be a potentially expensive operation, especially when using ES5.
Note that current
cannot be invoked on objects that aren't drafts.
Example​
The following example shows the effect of current
(and original
):
const base = {
x: 0
}
const next = produce(base, draft => {
draft.x++
const orig = original(draft)
const copy = current(draft)
console.log(orig.x)
console.log(copy.x)
setTimeout(() => {
// this will execute after the produce has finished!
console.log(orig.x)
console.log(copy.x)
}, 100)
draft.x++
console.log(draft.x)
})
console.log(next.x)
// This will print
// 0 (orig.x)
// 1 (copy.x)
// 2 (draft.x)
// 2 (next.x)
// 0 (after timeout, orig.x)
// 1 (after timeout, copy.x)