current()
Get the current value from a draft.
Usage
The current()
API provides developers with a way to capture the current state of a draft within the state management process. This function creates a copy of the state at the exact point in time it is called, without the draft's Proxy wrappers. This can be extremely beneficial for debugging, as it allows developers to inspect the state without the additional complexity of proxies.
Moreover, references to the object returned by current()
can be safely retained outside of the create
function without the risk of unintended side effects. It essentially gives you a snapshot of the state in the midst of mutation operations.
Here's how current()
behaves within the Mutative:
- Objects generated by
current()
will have structural sharing with their original counterparts wherever no modifications have been made. - If a draft has not been changed, it is usually true that
original(draft)
will be strictly equal tocurrent(draft)
, although this is not a strict guarantee. - Any subsequent alterations to the draft will not impact the snapshot provided by
current()
, with the exception of undraftable object references that remain mutable. - Objects retrieved via
current()
are not frozen.
const baseState = {
foo: 'bar',
list: [{ text: 'todo' }],
};
const state = create(baseState, (draft) => {
draft.foo = 'foobar';
draft.list.push({ text: 'learning' });
expect(current(draft.list)).toEqual([{ text: 'todo' }, { text: 'learning' }]);
});
It is important to note that current()
should be used judiciously. It is a potentially resource-intensive operation, especially if the draft is a large amount of data. Lastly, current()
must only be invoked on draft objects and not on original state objects or finalized states.