From 54cee009cf15a5086ad031da65278a7689230587 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Wed, 28 Jul 2021 22:18:00 +0200 Subject: [PATCH] fix: collect reactive effects ran in plugins --- __tests__/storePlugins.spec.ts | 38 +++++++++++++++++++++++++++++++++- src/store.ts | 32 +++++++++++++++------------- 2 files changed, 55 insertions(+), 15 deletions(-) diff --git a/__tests__/storePlugins.spec.ts b/__tests__/storePlugins.spec.ts index 6a7e1844..cc484b4f 100644 --- a/__tests__/storePlugins.spec.ts +++ b/__tests__/storePlugins.spec.ts @@ -1,6 +1,6 @@ import { createPinia, defineStore } from '../src' import { mount } from '@vue/test-utils' -import { App, computed, ref, toRef } from 'vue' +import { App, computed, ref, toRef, watch } from 'vue' declare module '../src' { export interface PiniaCustomProperties { @@ -11,6 +11,7 @@ declare module '../src' { globalA: string globalB: string shared: number + double: number } export interface PiniaCustomStateProperties { @@ -211,4 +212,39 @@ describe('store plugins', () => { useStore() }) + + it('run inside store effect', async () => { + const pinia = createPinia() + + // must call use after installing the plugin + pinia.use(({ store }) => ({ + // @ts-expect-error: invalid computed + double: computed(() => store.$state.n * 2), + })) + + const useStore = defineStore('main', { + state: () => ({ n: 1 }), + }) + + mount( + { + template: 'none', + setup() { + // create it inside of the component + useStore() + }, + }, + { global: { plugins: [pinia] } } + ).unmount() + + const store = useStore(pinia) + + const spy = jest.fn() + watch(() => store.double, spy, { flush: 'sync' }) + + expect(spy).toHaveBeenCalledTimes(0) + + store.n++ + expect(spy).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/store.ts b/src/store.ts index 766022cf..491250d2 100644 --- a/src/store.ts +++ b/src/store.ts @@ -537,20 +537,7 @@ function createSetupStore< // apply all plugins pinia._p.forEach((extender) => { if (__DEV__ && IS_CLIENT) { - const extensions = extender({ - store, - app: pinia._a, - pinia, - // @ts-expect-error - options: optionsForPlugin, - }) - Object.keys(extensions || {}).forEach((key) => - store._customProperties.add(key) - ) - assign(store, extensions) - } else { - assign( - store, + const extensions = scope.run(() => extender({ store, app: pinia._a, @@ -558,6 +545,23 @@ function createSetupStore< // @ts-expect-error options: optionsForPlugin, }) + )! + Object.keys(extensions || {}).forEach((key) => + store._customProperties.add(key) + ) + assign(store, extensions) + } else { + assign( + store, + scope.run(() => + extender({ + store, + app: pinia._a, + pinia, + // @ts-expect-error + options: optionsForPlugin, + }) + )! ) } }) -- 2.47.2