How to watch for when a store is rehydrated using Pinia + VueUse useLocalstorage

171 views Asked by At

I cannot find documentation about if there's an event raised (or a watch moment) when the in-memory store gets rehydrated from the LocalStorage during the page-load cycle of a Vue3 app booting.

I am using Pinia and defining the store with VueUse useLocalstorage e.g.

import {useLocalStorage} from "@vueuse/core"
export const useActiveProjectStore = defineStore('project', () => {
  const project = useLocalStorage('pinia/project', {})
  return { project }
})

The reason I want to listen for the reload is that my "project" object structure has a JS Date property in it, which gets converted to ISO string by the default serialiser JSON.stringify during storage. After reloading the app from scratch, that project property is now a string - i.e. the process isn't symmetrical. Therefore I wanted to catch the "reload" moment, and reconstruct the new Date() from the ISO string before returning the reactive object reference.

I know there is a top-level Date serialiser which does this automatically [source], for a single Date stored in a store, but my Date type property is nested inside a deeper structure so useStorage() chooses the JSON parser [ref].

I can see there Pinia has a state subscriber ref, but I think this is at the wrong level, as changes would be triggered also by updating the store from the app? Perhaps I could detect the initial instantiation from undefined to an object.

I can also see there are on-write events in the useStorage code [ ref1 and ref2 ]. But I can't see on-read.

I guess I could wrap the standard serialiser with a custom one which re-implements the standard JSON and does my specific transform or emits an event. But I'd rather avoid re-implementing parts of it just to hook into it.

serializer: {
    read: (v: any) => (v ? myTransformHook(JSON.parse(v)) : null),
    ...

Otherwise I may avoid having non-native objects in the structures, and always convert the ISO strings at the last minute (i.e. in various Vue components) which would require some injected handler to DRY it up.

Is there another clever way to make the JSON parse/stringify symmetric for Dates?

0

There are 0 answers