pinia-plugin-persistedstate: [nuxt] Pinia State doesn't persist when set from middleware
Describe the bug
This is my Pinia module:
import { defineStore } from "pinia";
export const useStore = defineStore("store", {
state: () => ({
token: '',
}),
actions: {
setToken(token: string) {
this.token = token;
}
},
persist: true
});
I set the state with setToken
function from the middleware
import {useStore} from "~/store/useStore";
export default defineNuxtRouteMiddleware(() => {
const store = useStore();
console.log('store.token1', store.token)
store.setToken('token')
console.log('store.token2', store.token)
});
Now on first app reload I would expect to see logs:
store.token1
store.token2 token
and on the second reload I would expect to see
store.token1 token store.token2 token
Instead I see:
Reproduction
https://github.com/d0peCode/nuxt3-pinia-middleware-issue
System Info
MacOS, Chrome
Used Package Manager
npm
Validations
- Follow our Code of Conduct
- Read the Contributing Guide.
- Check that there isn’t already an issue that reports the same bug to avoid creating a duplicate.
- The provided reproduction is a minimal reproducible of the bug.
About this issue
- Original URL
- State: open
- Created a year ago
- Comments: 24 (13 by maintainers)
you can do this
https://nuxt.com/docs/guide/directory-structure/middleware
This was the missing piece, thanks!!
I’m using a
check-auth.global.ts
middleware to refresh and store the session token and faced this issue as well.Just adding the
$persist
method after refreshing the token fixed my issue.Now its okay with adding middleware to this.
Now middleware.
I have done a lot of stupid things. 😦 after trying several possibilities, I found that just using it
store.$persist()
is enough. just like your code @d0peCode :I’m sorry that my thought is wrong before you explained. but the good news is that I have an idea, and I’m trying to solve it tomorrow.
PRs are always welcome 😃
That being said, keep in mind the nuxt module is an implementation of the base plugin, to work easily with Nuxt, and for most uses. Not everyone uses middleware and modify pinia stores in there.
So, yes, the library is SSR friendly with most use cases.
There are lots of cases that could be improved on the nuxt part, but the nuxt implementation is very simple. Keep in mind most of it is my work, on my free time, over nights, so I’d ask to stay respectful, for me and everyone who has contributed so far.
SSR is a very complex topic, and Nuxt still changes a lot. Keeping server and client in sync is ridiculously difficult, let alone middleware or server components… The Nuxt module was created when Nuxt3 was released officially, and docs were not even complete. Nuxt module docs are still not complete, and unit testing is still in RFC!
tl;dr: be respectful. the module fulfils most people’s needs (ssr included) and there will be improvement eventually.
also thanks @Abernethy-BY & @MZ-Dlovely for the answers 👍