Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The custom storage is inited during define instead of use, which is imcompitible with hooks. #44

Open
mmis1000 opened this issue May 26, 2022 · 1 comment

Comments

@mmis1000
Copy link

The custom storage is a Object parameter of pinia-plugin-persist

// this will blow up in nuxt SSR because it is not in a component.
const token = useCookie<string>('userToken', rawEncode)
const cookiesStorage = {
  setItem (_key: string, state: string) {
    try {
      token.value = JSON.parse(state).userToken
    } catch (err) {
      return undefined
    }
  },
  getItem (_key: string) {
    try {
      return JSON.stringify({ userToken: token.value })
    } catch (err) {
      return undefined
    }
  }
}
const useStore = defineStore({
  // ...
  persist: {
    enabled: true,
    strategies: [
      {
        storage: cookiesStorage,
        paths: ['accessToken']
      },
    ],
  }
}

It runs before the useStore.

But this is problematic when using with SSR frameworks.

Because SSR frameworks (such as nuxt) relies on useSSRContext to retrieve of information about current request.
Which isn't available outside of component life cycle.

My current hack about this is

const useStore = defineStore({
  // ...
    strategies: [
      {
        get storage () { return getCookiesStorage() as unknown as Storage },
        paths: ['userToken']
      }
    ]
  // ...
})

To delay the deference of getCookiesStorage and prevent it from crash the server.
But that isn't a proper usage at all.

I think this should be changed to (or as an alternative option) a factory function that called during useStore, so it don't cause probelm.

@edwh
Copy link

edwh commented Jun 18, 2022

@mmis1000 Thanks, I'm also seeing this, and your issue report is very clear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants