Global onMounted for Pinia initialisation?

I have an initialisation method on my Pinia store that I want to invoke before any other store stuff is invoked. I am currently using onMounted on a header component but it feels like a hack and doesn't always fire. AppHeader.vue script setup...
onMounted(async () => {
await authStore.initUser();
});
onMounted(async () => {
await authStore.initUser();
});
Is there a better approach for global store initialisation? maybe onMounted for the app.vue? or in defineNuxtConfig 'ready' hook?
4 Replies
Julien
Julien2y ago
Do you mean you want to populate a store or do some stuffs before rendering the whole app ? In that case, you can use a defineNuxtPlugin to do things before rendering the app btw, the plugin can be universal/server/client, using onMounted will only work client-side
JavascriptMick
I'm using Nuxt 3, defineNuxtPlugin doesn't work right? I tried this...
hooks: {
'ready': async () => {
const authStore = useAuthStore();
await authStore.initUser();
}
},
hooks: {
'ready': async () => {
const authStore = useAuthStore();
await authStore.initUser();
}
},
but useAuthStore is not defined 😦
Julien
Julien2y ago
it should. Consider defineNuxtPlugin as a part of main.ts in a vue app.
export default defineNuxtPlugin(async (nuxtApp) => {
const authStore = useAuthStore();
await authStore.initUser();
})
export default defineNuxtPlugin(async (nuxtApp) => {
const authStore = useAuthStore();
await authStore.initUser();
})
JavascriptMick
ok so I did the plugin and it does invoke my store function but now inside the store function, the trpc client supplied by trpc-nuxt is not available via useNuxtApp
const { $client } = useNuxtApp();
const { dbUser } = await $client.auth.getDBUser.query();
const { $client } = useNuxtApp();
const { dbUser } = await $client.auth.getDBUser.query();
[nuxt] [request error] [unhandled] [500] Cannot read properties of undefined (reading 'auth') for now I have resolved this by specifying onMounted for every page where the user needs to be initialised. The store function is idempotent and does no work if it is not required. This seems to work. Thanks for your help @chakraecho
Want results from more Discord servers?
Add your server