Skip to content

Commit 465d222

Browse files
LemonAppleMoposva
andauthored
fix(subscriptions): allow removing subscriptions inside them (#990)
Co-authored-by: Eduardo San Martin Morote <[email protected]>
1 parent b332529 commit 465d222

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

packages/pinia/__tests__/subscriptions.spec.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -272,4 +272,33 @@ describe('Subscriptions', () => {
272272
store.$state
273273
)
274274
})
275+
276+
it('subscribe once with patch', () => {
277+
const spy1 = jest.fn()
278+
const spy2 = jest.fn()
279+
const store = useStore()
280+
function once() {
281+
const unsubscribe = store.$subscribe(
282+
() => {
283+
spy1()
284+
unsubscribe()
285+
},
286+
{ flush: 'sync' }
287+
)
288+
}
289+
once()
290+
store.$subscribe(spy2, { flush: 'sync' })
291+
expect(spy1).toHaveBeenCalledTimes(0)
292+
expect(spy2).toHaveBeenCalledTimes(0)
293+
store.$patch((state) => {
294+
state.user = 'a'
295+
})
296+
expect(spy1).toHaveBeenCalledTimes(1)
297+
expect(spy2).toHaveBeenCalledTimes(1)
298+
store.$patch((state) => {
299+
state.user = 'b'
300+
})
301+
expect(spy1).toHaveBeenCalledTimes(1)
302+
expect(spy2).toHaveBeenCalledTimes(2)
303+
})
275304
})

packages/pinia/src/subscriptions.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ export function triggerSubscriptions<T extends _Method>(
3030
subscriptions: T[],
3131
...args: Parameters<T>
3232
) {
33-
subscriptions.forEach((callback) => {
33+
subscriptions.slice().forEach((callback) => {
3434
callback(...args)
3535
})
3636
}

0 commit comments

Comments
 (0)