Seb-L / pinia-plugin-persist

Persist pinia state data in sessionStorage or other storages.
https://Seb-L.github.io/pinia-plugin-persist/
MIT License
214 stars 37 forks source link

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

Open mmis1000 opened 2 years ago

mmis1000 commented 2 years ago

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 commented 2 years ago

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