]> 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 <posva@users.noreply.github.com>
Sat, 10 Apr 2021 15:17:15 +0000 (17:17 +0200)
Fix #429, Fix #430

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

index ae2cb77e9a7050dc2b375aa17c7b2cc3e2c6e2ab..f0e99b90a24313f38824bd868e5899397c387e4f 100644 (file)
@@ -37,9 +37,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 6c17e12651756f2a05e53a121cc008b6fa87148c..5aabbbdc43d7c57c413cff7fb80bfc6826bf9c34 100644 (file)
@@ -47,4 +47,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 fd50d672a9bf4dcc37c0674b57984cd0015706a6..3f935806498d6dd4ad16726125b4e0f3a9cf5b16 100644 (file)
@@ -132,12 +132,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)
         }
       },
       {
@@ -156,7 +151,6 @@ function initStore<Id extends string, S extends StateTree>(
   }
 
   function $reset() {
-    subscriptions = []
     pinia.state.value[$id] = buildState()
   }
 
index 9ab1fcc73ecc34ceec6c46144a8b58e3d0ccd3be..fbb8498210a52fe410f4fe7efd06a1d32ab9d8af 100644 (file)
@@ -66,8 +66,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