T
TanStack11mo ago
absent-sapphire

How to deserialize dates with createAsyncStoragePersister?

I am using Indexed DB to persist the cache. I have an issue where dayjs objects are stored in the cache, and when I reload the page, it breaks because those objects are returned as strings. I have been researching and found that createAsyncStoragePersister has serialize and deserialize properties to customize this. I also saw that using a library like superjson is recommended to achieve this. However, I haven’t found any code examples showing how to implement it. Any ideas? I would appreciate a small code example on how to implement this in createAsyncStoragePersister. This is my persister
import { del, get, set } from 'idb-keyval'

const persister = createAsyncStoragePersister({
storage: {
setItem: async (key, value) => set(key, value),
removeItem: async (key) => del(key),
getItem: async (key) => get(key),
},
})
import { del, get, set } from 'idb-keyval'

const persister = createAsyncStoragePersister({
storage: {
setItem: async (key, value) => set(key, value),
removeItem: async (key) => del(key),
getItem: async (key) => get(key),
},
})
2 Replies
fascinating-indigo
fascinating-indigo11mo ago
You can pass superjson's stringify and parse to those options, but you would need to register your own "recipe" for dayjs objects See https://github.com/flightcontrolhq/superjson?tab=readme-ov-file#recipes
absent-sapphire
absent-sapphireOP11mo ago
import { del, get, set } from 'idb-keyval'
import dayjs, { Dayjs } from 'dayjs'
import superjson from 'superjson'

superjson.registerCustom<Dayjs, string>(
{
isApplicable: (value): value is Dayjs => dayjs.isDayjs(value),
serialize: (value: Dayjs) => value.toISOString(),
deserialize: (value) => dayjs(value),
},
'dayjs',
)

const persister = createAsyncStoragePersister({
serialize: superjson.stringify,
deserialize: superjson.parse,
storage: {
setItem: async (key, value) => set(key, value),
removeItem: async (key) => del(key),
getItem: async (key) => get(key),
},
})
import { del, get, set } from 'idb-keyval'
import dayjs, { Dayjs } from 'dayjs'
import superjson from 'superjson'

superjson.registerCustom<Dayjs, string>(
{
isApplicable: (value): value is Dayjs => dayjs.isDayjs(value),
serialize: (value: Dayjs) => value.toISOString(),
deserialize: (value) => dayjs(value),
},
'dayjs',
)

const persister = createAsyncStoragePersister({
serialize: superjson.stringify,
deserialize: superjson.parse,
storage: {
setItem: async (key, value) => set(key, value),
removeItem: async (key) => del(key),
getItem: async (key) => get(key),
},
})
Works for me, that was the code. Thanks

Did you find this page helpful?