N
Nuxt2mo ago
Zeeeth

Add data to store on Page Refresh

Lets say i have an authentication, when the user login i get a token and i store that in a session cookie. I also add the user-information to a Pinia UserStore. All good. But when the user refreshes the page i would need to use that session cookie to first fetch the current user from the API and once again populate the UserStore with the user data. Where do i place this code? I've seen examples on both just placing that code in App.vue, or creating a plugin to populate the data. Is there any Best Practice for doing this SSR-friendly? Placing it directly in App.vue seem like a OK solution, but feels like it very fast could grow a bit depending on the session data that need to be fetched.
7 Replies
lucky.
lucky.2mo ago
I think the best way is to create / add middleware on pages requiring authentication, and then fetch your user's information if it's not already present in the userStore.
joe_black_unlucky
You can use pinia persisted state plugin to store your userStore in a cookie
npm
pinia-plugin-persistedstate
Configurable persistence and rehydration of Pinia stores.. Latest version: 4.0.2, last published: 13 days ago. Start using pinia-plugin-persistedstate in your project by running npm i pinia-plugin-persistedstate. There are 187 other projects in the npm registry using pinia-plugin-persistedstate.
Danny Vogel
Danny Vogel2mo ago
I had the same issue and placed it in a plugin that checks for the token and if it exists, loads the store. Since this is done server-side, the user data is available immediately.
Single
Single2mo ago
We solve this by using pinia-plugin-persistedstate. It saves the token to the sessionStoreage / localStorage and loads it for you automatically. It has a callback method you can use to request the user for the token from the backend once the store is loaded:
...},
persist: {
afterRestore: async ctx => {
const u = await loadYourUser(ctx.store.token)
}
}
...},
persist: {
afterRestore: async ctx => {
const u = await loadYourUser(ctx.store.token)
}
}
Single
Single2mo ago
Apparently, afterRestore has been renamed to afterHydrate in the latest version
Zeeeth
ZeeethOP2mo ago
Thank you all for your input! I think i will give a plugin a go since i want this to work with SSR.
Want results from more Discord servers?
Add your server