Last active
February 29, 2024 07:37
-
-
Save wobsoriano/902cce12639a1faa0764542e3732fce5 to your computer and use it in GitHub Desktop.
nuxtServerInit like implementation for Pinia
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { defineStore } from 'pinia' | |
export const useAuthStore = defineStore({ | |
id: 'auth', | |
state: () => ({ | |
isAuthenticated: false, | |
user: null | |
}), | |
actions: { | |
async nuxtServerInit() { | |
const user = await this.$axios.get('/api/user') | |
this.$patch({ | |
isAuthenticated: true, | |
user | |
}) | |
} | |
} | |
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useAuthStore } from '~/store/auth' | |
export default async function ({ $pinia }) { | |
if (process.server) { | |
const store = useAuthStore($pinia) | |
await store.nuxtServerInit() | |
} | |
} | |
// Add this file to nuxt.config.js | |
// { router: { middleware: ['nuxt-server-init'] } } |
A plugin won't wait for the data to be fetch before loading the page?
I don't know if it's just the recent versions of nuxt but I'm not being able to call useStore inside defineNuxtPlugin
, neither access a valid $pinia
on nuxtApp
param
@LeonardoRick yes you can.
in the nuxt.config we can import store so that it's available throughout the application
imports: { dirs: ['./stores'] }
then the plugins/......
export default defineNuxtPlugins((nuxtApp) => {
const exampleStore = useExampleStore()
})
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should use nuxt plugins instead of middleware.
Because this middware will be invoked every time route changes (of course you already check
process.server
, but a plugin should be more suitable)