Skip to content

Commit

Permalink
fix: install plugins after app is set (vuejs#1063)
Browse files Browse the repository at this point in the history
  • Loading branch information
21skills committed Jun 24, 2022
1 parent 6125f6c commit 4c45ec0
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 25 deletions.
26 changes: 23 additions & 3 deletions packages/pinia/src/createPinia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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<string, StoreGeneric>(),
state,
Expand Down
8 changes: 8 additions & 0 deletions packages/pinia/src/rootStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
*
Expand Down
46 changes: 24 additions & 22 deletions packages/pinia/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down

0 comments on commit 4c45ec0

Please sign in to comment.