Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions __tests__/current.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 => {
Expand Down
50 changes: 25 additions & 25 deletions src/core/current.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,34 +23,34 @@ export function current(value: Draft<any>): 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
}