@@ -95,7 +95,7 @@ const computedImpl: ComputedStateImpl = (compute, opts) => (f) => {
9595 return ( set , get , api ) => {
9696 const equalityFn = opts ?. equalityFn ?? shallow
9797
98- function computeAndMerge ( state : T | ( T & A ) ) : T & A {
98+ function computeAndMerge ( state : T | ( T & A ) , mutateInPlace = false ) : T & A {
9999 // Calculate the new computed state.
100100 const computedState = compute ( state )
101101
@@ -107,7 +107,7 @@ const computedImpl: ComputedStateImpl = (compute, opts) => (f) => {
107107 }
108108 }
109109
110- return Object . assign ( state , computedState )
110+ return mutateInPlace ? Object . assign ( state , computedState ) : { ... state , ... computedState }
111111 }
112112
113113 const _api = api as Mutate < StoreApi < T > , [ [ "chrisvander/zustand-computed" , A ] ] >
@@ -123,7 +123,12 @@ const computedImpl: ComputedStateImpl = (compute, opts) => (f) => {
123123 set ( ( state ) => {
124124 const newState = typeof arg === "function" ? arg ( state ) : arg
125125 if ( ! shouldRecomputeFn ( state , newState ) ) return newState
126- return computeAndMerge ( Object . assign ( state , newState ) )
126+ if ( typeof arg === "function" && newState === undefined ) {
127+ // Immer producers mutate the existing draft and return `undefined`.
128+ // In that flow we must mutate in place rather than returning a new object.
129+ return computeAndMerge ( state , true )
130+ }
131+ return computeAndMerge ( { ...state , ...newState } )
127132 } , replace )
128133 return
129134 }
@@ -138,7 +143,7 @@ const computedImpl: ComputedStateImpl = (compute, opts) => (f) => {
138143
139144 _api . setState = setState
140145 const st = f ( setState , get , _api )
141- return Object . assign ( { } , st , compute ( st ) )
146+ return { ... st , ... compute ( st ) }
142147 }
143148}
144149
0 commit comments