diff --git a/packages/pinia/src/createPinia.ts b/packages/pinia/src/createPinia.ts index f105460e50..796d1c706a 100644 --- a/packages/pinia/src/createPinia.ts +++ b/packages/pinia/src/createPinia.ts @@ -18,6 +18,8 @@ export function createPinia(): Pinia { let _p: Pinia['_p'] = [] // plugins added before calling app.use(pinia) let toBeInstalled: PiniaPlugin[] = [] + let afterInitializeCallbacks: ((app: App) => void)[] = [] + let _a: App | null = null const pinia: Pinia = markRaw({ install(app: App) { @@ -47,9 +49,27 @@ export function createPinia(): Pinia { }, _p, - // it's actually undefined here - // @ts-expect-error - _a: null, + + get _a() { + return _a! + }, + set _a(app) { + _a = app + + if (app) { + afterInitializeCallbacks.forEach((cb) => cb(app)) + afterInitializeCallbacks = [] + } + }, + + afterAppInit(cb: (app: App) => void) { + if (_a) { + cb(_a) + } else { + afterInitializeCallbacks.push(cb) + } + }, + _e: scope, _s: new Map(), state, diff --git a/packages/pinia/src/rootStore.ts b/packages/pinia/src/rootStore.ts index 0509a5c8eb..d5ec8f8fe6 100644 --- a/packages/pinia/src/rootStore.ts +++ b/packages/pinia/src/rootStore.ts @@ -57,6 +57,14 @@ export interface Pinia { */ use(plugin: PiniaPlugin): Pinia + /** + * Executes callback after pinia._a is set, or immediately, if it is set already + * + * @internal + * @param cb - callback to execute + */ + afterAppInit(cb: (app: App) => void): void + /** * Installed store plugins * diff --git a/packages/pinia/src/store.ts b/packages/pinia/src/store.ts index d7156a0ea6..1df275aca5 100644 --- a/packages/pinia/src/store.ts +++ b/packages/pinia/src/store.ts @@ -676,34 +676,36 @@ function createSetupStore< } // apply all plugins - pinia._p.forEach((extender) => { - /* istanbul ignore else */ - if (__DEV__ && IS_CLIENT) { - const extensions = scope.run(() => - extender({ - store, - app: pinia._a, - pinia, - options: optionsForPlugin, - }) - )! - Object.keys(extensions || {}).forEach((key) => - store._customProperties.add(key) - ) - assign(store, extensions) - } else { - assign( - store, - scope.run(() => + pinia.afterAppInit((app) => { + pinia._p.forEach((extender) => { + /* istanbul ignore else */ + if (__DEV__ && IS_CLIENT) { + const extensions = scope.run(() => extender({ store, - app: pinia._a, + app, pinia, options: optionsForPlugin, }) )! - ) - } + Object.keys(extensions || {}).forEach((key) => + store._customProperties.add(key) + ) + assign(store, extensions) + } else { + assign( + store, + scope.run(() => + extender({ + store, + app, + pinia, + options: optionsForPlugin, + }) + )! + ) + } + }) }) if (