From ec78e22795ee755dacd176c68a5112b09edac142 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Fri, 9 Jul 2021 11:59:31 +0200 Subject: [PATCH] refactor: detached in subscribeAction --- src/store.ts | 45 ++++++++++++++++++++++++++++----------------- 1 file changed, 28 insertions(+), 17 deletions(-) diff --git a/src/store.ts b/src/store.ts index aa28b93a..95d0c707 100644 --- a/src/store.ts +++ b/src/store.ts @@ -14,7 +14,6 @@ import { isRef, isReactive, effectScope, - onScopeDispose, EffectScope, onUnmounted, ComputedRef, @@ -408,7 +407,7 @@ export interface DefineSetupStoreOptions< hydrate?(store: Store, initialState: S | undefined): void } -function isComputed(o: any) { +function isComputed(o: any): o is ComputedRef { return o && o.effect && o.effect.computed } @@ -425,7 +424,7 @@ function createSetupStore< // @ts-expect-error hydrate = innerPatch, }: DefineSetupStoreOptions = {} -): Store { +): Store { const pinia = getActivePinia() let scope!: EffectScope @@ -538,22 +537,28 @@ function createSetupStore< ) } + // TODO: refactor duplicated code for subscriptions function $subscribe(callback: SubscriptionCallback, detached?: boolean) { subscriptions.push(callback) - if (!detached) { - if (getCurrentInstance()) { - onUnmounted(() => { - const idx = subscriptions.indexOf(callback) - if (idx > -1) { - subscriptions.splice(idx, 1) - } - }) + const removeSubscription = () => { + const idx = subscriptions.indexOf(callback) + if (idx > -1) { + subscriptions.splice(idx, 1) } } + + if (!detached && getCurrentInstance()) { + onUnmounted(removeSubscription) + } + + return removeSubscription } - function $onAction(callback: StoreOnActionListener) { + function $onAction( + callback: StoreOnActionListener, + detached?: boolean + ) { actionSubscriptions.push(callback) const removeSubscription = () => { @@ -563,8 +568,8 @@ function createSetupStore< } } - if (getCurrentInstance()) { - onScopeDispose(removeSubscription) + if (!detached && getCurrentInstance()) { + onUnmounted(removeSubscription) } return removeSubscription @@ -664,9 +669,15 @@ function createSetupStore< // apply all plugins pinia._p.forEach((extender) => { if (__DEV__ && IS_CLIENT) { - // @ts-expect-error: conflict between A and ActionsTree - // TODO: completely different options... - const extensions = extender({ store, app: pinia._a, pinia, options }) + const extensions = extender({ + // @ts-expect-error: conflict between A and ActionsTree + store, + app: pinia._a, + pinia, + // TODO: completely different options... + // @ts-expect-error + options, + }) Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key) ) -- 2.47.2