From 60df4d51e3c1ca7980c452d4d38eeac88b948acf Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Fri, 9 Apr 2021 19:06:27 +0200 Subject: [PATCH] fix(store): avoid multiple subscriptions call Fix #429, Fix #430 --- __tests__/store.spec.ts | 3 ++- __tests__/subscriptions.spec.ts | 28 ++++++++++++++++++++++++++++ src/store.ts | 8 +------- src/types.ts | 3 +-- 4 files changed, 32 insertions(+), 10 deletions(-) diff --git a/__tests__/store.spec.ts b/__tests__/store.spec.ts index ae2cb77e..f0e99b90 100644 --- a/__tests__/store.spec.ts +++ b/__tests__/store.spec.ts @@ -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: { diff --git a/__tests__/subscriptions.spec.ts b/__tests__/subscriptions.spec.ts index 6c17e126..5aabbbdc 100644 --- a/__tests__/subscriptions.spec.ts +++ b/__tests__/subscriptions.spec.ts @@ -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) + }) + }) }) diff --git a/src/store.ts b/src/store.ts index fd50d672..3f935806 100644 --- a/src/store.ts +++ b/src/store.ts @@ -132,12 +132,7 @@ function initStore( () => 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( } function $reset() { - subscriptions = [] pinia.state.value[$id] = buildState() } diff --git a/src/types.ts b/src/types.ts index 9ab1fcc7..fbb84982 100644 --- a/src/types.ts +++ b/src/types.ts @@ -66,8 +66,7 @@ export interface StoreWithState { $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 -- 2.47.3