Skip to content
Myr

fix: unnecessary draft creation

Before adoption: this commit came in with the history the project adopted, so no landing records it.

When a draft wraps another draft, it must be careful to never create a draft when accessing its base state. Also, when the wrapper draft is modified, it copies the wrapped draft at that point in time, which means you should avoid passing a draft to an async producer. Fixes #343

authored by Alec Larson · committed by Alec Larson · parent fb12428 · Browse files · 2 files+32 added−8 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+32 added−8 removed

  • other:+32 added−8 removed

2 files+32 added−8 removed

modified:src/es5.js+17 added-4 removed
66 unmodified lines
67function source(state) {68 return state.copy || state.base69}7071// Access a property without creating an Immer draft.72function peek(draft, prop) {73 const state = draft[DRAFT_STATE]74 if (state && !state.finalizing) {75 state.finalizing = true76 const value = draft[prop]77 state.finalizing = false78 return value79 }80 return draft[prop]81}8283function get(state, prop) {84 assertUnrevoked(state)73 const value = source(state)[prop]74 // Drafts are only created for proxyable values that exist in the base state.75 if (!state.finalizing && value === state.base[prop] && isDraftable(value)) {85 const value = peek(source(state), prop)86 if (state.finalizing) return value87 // Create a draft if the value is unmodified.88 if (value === peek(state.base, prop) && isDraftable(value)) {89 prepareCopy(state)90 return (state.copy[prop] = createProxy(value, state))91 }92 return value
2 unmodified lines
95function set(state, prop, value) {96 assertUnrevoked(state)97 state.assigned[prop] = true98 if (!state.modified) {86 if (is(source(state)[prop], value)) return99 if (is(value, peek(source(state), prop))) return100 markChanged(state)101 prepareCopy(state)102 }103 state.copy[prop] = value
160 unmodified lines
modified:src/proxy.js+15 added-4 removed