diff --git a/__tests__/current.js b/__tests__/current.js index cac6ab76..0b299285 100644 --- a/__tests__/current.js +++ b/__tests__/current.js @@ -57,6 +57,25 @@ function runTests(name) { }) }) + it("keeps drafting after a snapshot throws", () => { + const base = {nested: {count: 0}} + const error = new Error("Cannot read the snapshot") + const next = produce(base, draft => { + draft.temporary = { + get value() { + throw error + } + } + expect(() => current(draft)).toThrow(error) + + delete draft.temporary + draft.nested.count++ + }) + + expect(base.nested.count).toBe(0) + expect(next.nested.count).toBe(1) + }) + it("returns original without changes", () => { const base = {} produce(base, draft => { diff --git a/src/core/current.ts b/src/core/current.ts index 39ad03fb..3f972de7 100644 --- a/src/core/current.ts +++ b/src/core/current.ts @@ -23,34 +23,34 @@ export function current(value: Draft): any { function currentImpl(value: any): any { if (!isDraftable(value) || isFrozen(value)) return value const state: ImmerState | undefined = value[DRAFT_STATE] - let copy: any - let strict = true // Default to strict for compatibility + if (state && !state.modified_) return state.base_ + + const wasFinalized = state?.finalized_ ?? false if (state) { - if (!state.modified_) return state.base_ // Optimization: avoid generating new drafts during copying state.finalized_ = true - copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_) - strict = state.scope_.immer_.shouldUseStrictIteration() - } else { - copy = shallowCopy(value, true) } - // Rebuild Sets so snapshots replace their draft values in insertion order. - const source = copy - const setCopy = isSet(copy) - if (setCopy) copy = new Set() - // Children a draft still shares with its base hold no drafts, so they are reused as is - const base = state && !setCopy ? state.base_ : undefined - each( - source, - (key, childValue) => { - if (base !== undefined && childValue === get(base, key, state!.type_)) - return - set(copy, key, currentImpl(childValue)) - }, - strict - ) - if (state) { - state.finalized_ = false + try { + const source = shallowCopy( + value, + state?.scope_.immer_.useStrictShallowCopy_ ?? true + ) + // Rebuild Sets so snapshots replace their draft values in insertion order. + const setCopy = isSet(source) + const copy = setCopy ? new Set() : source + // Children a draft still shares with its base hold no drafts, so they are reused as is + const base = setCopy ? undefined : state?.base_ + each( + source, + (key, childValue) => { + if (base !== undefined && childValue === get(base, key, state!.type_)) + return + set(copy, key, currentImpl(childValue)) + }, + state?.scope_.immer_.shouldUseStrictIteration() ?? true + ) + return copy + } finally { + if (state) state.finalized_ = wasFinalized } - return copy }