foo: 'foo',
a: { b: 'string' },
},
+ list: [] as number[],
}),
})()
}
foo: 'foo',
a: { b: 'string' },
},
+ list: [],
+ })
+ })
+
+ it('patches using a function', () => {
+ const store = useStore()
+ store.$patch((state) => {
+ state.a = !state.a
+ state.list.push(1)
+ })
+ expect(store.$state).toEqual({
+ a: false,
+ nested: {
+ foo: 'foo',
+ a: { b: 'string' },
+ },
+ list: [1],
})
})
foo: 'bar',
a: { b: 'string' },
},
+ list: [],
})
store.$patch({ nested: { a: { b: 'hello' } } })
expect(store.$state).toEqual({
foo: 'bar',
a: { b: 'hello' },
},
+ list: [],
})
})
foo: 'hello',
a: { b: 'string' },
},
+ list: [],
})
})
})
let isListening = true
let subscriptions: SubscriptionCallback<S>[] = []
- function $patch(partialState: DeepPartial<S>): void {
+ function $patch(stateMutation: (state: S) => void): void
+ function $patch(partialState: DeepPartial<S>): void
+ function $patch(
+ partialStateOrMutator: DeepPartial<S> | ((state: S) => void)
+ ): void {
+ let partialState: DeepPartial<S> = {}
+ let type: string
isListening = false
- innerPatch(pinia.state.value[$id], partialState)
+ if (typeof partialStateOrMutator === 'function') {
+ partialStateOrMutator(pinia.state.value[$id])
+ type = '🧩 patch'
+ } else {
+ innerPatch(pinia.state.value[$id], partialStateOrMutator)
+ partialState = partialStateOrMutator
+ type = '⤵️ patch'
+ }
isListening = true
// because we paused the watcher, we need to manually call the subscriptions
subscriptions.forEach((callback) => {
callback(
- { storeName: $id, type: '⤵️ patch', payload: partialState },
+ { storeName: $id, type, payload: partialState },
pinia.state.value[$id]
)
})
*/
$patch(partialState: DeepPartial<S>): void
+ /**
+ * Group multiple changes into one function. Useful when mutating objects like
+ * Sets or arrays and applying an object patch isn't practical, e.g. appending
+ * to an array.
+ *
+ * @param stateMutator - function that mutates `state`
+ */
+ $patch(stateMutator: (state: S) => void): void
+
/**
* Resets the store to its initial state by removing all subscriptions and
* building a new state object