]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
fix(subscriptions): allow removing subscriptions inside them (#990)
authorhxp971130 <32638462+LemonAppleMo@users.noreply.github.com>
Wed, 26 Jan 2022 09:59:18 +0000 (17:59 +0800)
committerGitHub <noreply@github.com>
Wed, 26 Jan 2022 09:59:18 +0000 (10:59 +0100)
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com>
packages/pinia/__tests__/subscriptions.spec.ts
packages/pinia/src/subscriptions.ts

index bfd36b3927ccefef208c3ce10036704445cac8c3..cacd8c2961511157ec7de05df197cfd5e6a851ee 100644 (file)
@@ -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)
+  })
 })
index 5dfd2620fa09409be3267f1832f1c540c97d2cc6..6dc46bb192d6f7ef7645bee1258c16a6670bc198 100644 (file)
@@ -30,7 +30,7 @@ export function triggerSubscriptions<T extends _Method>(
   subscriptions: T[],
   ...args: Parameters<T>
 ) {
-  subscriptions.forEach((callback) => {
+  subscriptions.slice().forEach((callback) => {
     callback(...args)
   })
 }