From: Eduardo San Martin Morote Date: Fri, 9 Apr 2021 17:06:27 +0000 (+0200) Subject: fix(store): avoid multiple subscriptions call X-Git-Tag: v2.0.0-alpha.12~2 X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=71404cb3ef6466c74b72c5fdb1075740a788a309;p=thirdparty%2Fvuejs%2Fpinia.git fix(store): avoid multiple subscriptions call Fix #429, Fix #430 --- diff --git a/__tests__/store.spec.ts b/__tests__/store.spec.ts index 3597f5a0..c94bcc13 100644 --- a/__tests__/store.spec.ts +++ b/__tests__/store.spec.ts @@ -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: { diff --git a/__tests__/subscriptions.spec.ts b/__tests__/subscriptions.spec.ts index e1bd2b80..0e4b9ca0 100644 --- a/__tests__/subscriptions.spec.ts +++ b/__tests__/subscriptions.spec.ts @@ -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) + }) + }) }) diff --git a/src/store.ts b/src/store.ts index 5e43d8d3..801906cd 100644 --- a/src/store.ts +++ b/src/store.ts @@ -126,12 +126,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) } }, { @@ -150,7 +145,6 @@ function initStore( } function $reset() { - subscriptions = [] pinia.state.value[$id] = buildState() } diff --git a/src/types.ts b/src/types.ts index 14149df5..bc81a256 100644 --- a/src/types.ts +++ b/src/types.ts @@ -81,8 +81,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