Skip to content

Commit

Permalink
fix(subscriptions): allow removing subscriptions inside them (#990)
Browse files Browse the repository at this point in the history
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com>
  • Loading branch information
LemonAppleMo and posva committed Jan 26, 2022
1 parent b332529 commit 465d222
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
29 changes: 29 additions & 0 deletions packages/pinia/__tests__/subscriptions.spec.ts
Expand Up @@ -272,4 +272,33 @@ describe('Subscriptions', () => {
store.$state
)
})

it('subscribe once with patch', () => {
const spy1 = jest.fn()
const spy2 = jest.fn()
const store = useStore()
function once() {
const unsubscribe = store.$subscribe(
() => {
spy1()
unsubscribe()
},
{ flush: 'sync' }
)
}
once()
store.$subscribe(spy2, { flush: 'sync' })
expect(spy1).toHaveBeenCalledTimes(0)
expect(spy2).toHaveBeenCalledTimes(0)
store.$patch((state) => {
state.user = 'a'
})
expect(spy1).toHaveBeenCalledTimes(1)
expect(spy2).toHaveBeenCalledTimes(1)
store.$patch((state) => {
state.user = 'b'
})
expect(spy1).toHaveBeenCalledTimes(1)
expect(spy2).toHaveBeenCalledTimes(2)
})
})
2 changes: 1 addition & 1 deletion packages/pinia/src/subscriptions.ts
Expand Up @@ -30,7 +30,7 @@ export function triggerSubscriptions<T extends _Method>(
subscriptions: T[],
...args: Parameters<T>
) {
subscriptions.forEach((callback) => {
subscriptions.slice().forEach((callback) => {
callback(...args)
})
}

0 comments on commit 465d222

Please sign in to comment.