]> git.ipfire.org Git - thirdparty/vuejs/pinia.git/commitdiff
fix(store): avoid multiple subscriptions call
authorEduardo San Martin Morote <posva13@gmail.com>
Fri, 9 Apr 2021 17:06:27 +0000 (19:06 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Fri, 9 Apr 2021 17:06:27 +0000 (19:06 +0200)
Fix #429, Fix #430

__tests__/store.spec.ts
__tests__/subscriptions.spec.ts
src/store.ts
src/types.ts

index 3597f5a0d8ae555102c9b58f2702da80eff67d62..c94bcc130a1cb030401ce6f91b4cd3c3ab7ed79a 100644 (file)
@@ -60,9 +60,10 @@ describe('Store', () => {
     store.$state.a = false
     const spy = jest.fn()
     store.$subscribe(spy)
+    expect(spy).not.toHaveBeenCalled()
     store.$reset()
     store.$state.nested.foo = 'bar'
-    expect(spy).not.toHaveBeenCalled()
+    expect(spy).toHaveBeenCalledTimes(2)
     expect(store.$state).toEqual({
       a: true,
       nested: {
index e1bd2b807e2fb8e51880d513f85d97fcd081d647..0e4b9ca09a952235c4a60a41c2a4578dc83cf9e4 100644 (file)
@@ -43,4 +43,32 @@ describe('Subscriptions', () => {
     expect(func1).not.toHaveBeenCalled()
     expect(func2).toHaveBeenCalledTimes(1)
   })
+
+  describe('multiple', () => {
+    const useStore = defineStore({
+      id: 'main',
+      state: () => ({
+        name: 'Eduardo',
+      }),
+    })
+
+    it('triggers subscribe only once', async () => {
+      const s1 = useStore()
+      const s2 = useStore()
+
+      const spy1 = jest.fn()
+      const spy2 = jest.fn()
+
+      s1.$subscribe(spy1)
+      s2.$subscribe(spy2)
+
+      expect(spy1).toHaveBeenCalledTimes(0)
+      expect(spy2).toHaveBeenCalledTimes(0)
+
+      s1.name = 'Edu'
+
+      expect(spy1).toHaveBeenCalledTimes(1)
+      expect(spy2).toHaveBeenCalledTimes(1)
+    })
+  })
 })
index 5e43d8d3c8a9aaab3ef6288b862399754d284dd1..801906cdbde55bdde2b730ed83a944f94308ae24 100644 (file)
@@ -126,12 +126,7 @@ function initStore<Id extends string, S extends StateTree>(
       () => pinia.state.value[$id],
       (state) => {
         if (isListening) {
-          subscriptions.forEach((callback) => {
-            callback(
-              { storeName: $id, type: '🧩 in place', payload: {} },
-              state
-            )
-          })
+          callback({ storeName: $id, type: '🧩 in place', payload: {} }, state)
         }
       },
       {
@@ -150,7 +145,6 @@ function initStore<Id extends string, S extends StateTree>(
   }
 
   function $reset() {
-    subscriptions = []
     pinia.state.value[$id] = buildState()
   }
 
index 14149df5d4648d5425cd4ec39a01c89035baf392..bc81a256ecd0c884c4ec98e9792d469ba3002aa1 100644 (file)
@@ -81,8 +81,7 @@ export interface StoreWithState<Id extends string, S extends StateTree> {
   $patch(stateMutator: (state: S) => void): void
 
   /**
-   * Resets the store to its initial state by removing all subscriptions and
-   * building a new state object
+   * Resets the store to its initial state by building a new state object.
    */
   $reset(): void