Nuxt 3 persistent cache
I'm trying to convert the Nuxt SSR plugin example into a localstorage persister. But i'm getting stuck on the different QueryClients between the @tanstack/vue-query package and the @tanstack/query-core package.
Did anyone manage to get this to work in Nuxt 3?
This is my plugin at the moment but it fails on the QueryClient
Did anyone manage to get this to work in Nuxt 3?
This is my plugin at the moment but it fails on the QueryClient
import { QueryClient, DehydratedState, dehydrate, hydrate } from '@tanstack/query-core'
import { VueQueryPlugin, VueQueryPluginOptions } from '@tanstack/vue-query'
import { persistQueryClient } from '@tanstack/query-persist-client-core'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
import { useState } from '#app'
export default defineNuxtPlugin((nuxt) => {
const vueQueryState = useState<DehydratedState | null>('vue-query')
const options: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 24,
staleTime: 1000 * 60 * 60 * 24,
},
},
},
clientPersister: (queryClient: QueryClient) => {
return persistQueryClient({
queryClient,
persister: createSyncStoragePersister({storage: window.localStorage}),
})
},
}
nuxt.vueApp.use(VueQueryPlugin, options)
if (process.server) {
nuxt.hooks.hook('app:rendered', () => {
vueQueryState.value = dehydrate(queryClient)
})
}
if (process.client) {
nuxt.hooks.hook('app:created', () => {
hydrate(queryClient, vueQueryState.value)
})
}
}) import { QueryClient, DehydratedState, dehydrate, hydrate } from '@tanstack/query-core'
import { VueQueryPlugin, VueQueryPluginOptions } from '@tanstack/vue-query'
import { persistQueryClient } from '@tanstack/query-persist-client-core'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
import { useState } from '#app'
export default defineNuxtPlugin((nuxt) => {
const vueQueryState = useState<DehydratedState | null>('vue-query')
const options: VueQueryPluginOptions = {
queryClientConfig: {
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 24,
staleTime: 1000 * 60 * 60 * 24,
},
},
},
clientPersister: (queryClient: QueryClient) => {
return persistQueryClient({
queryClient,
persister: createSyncStoragePersister({storage: window.localStorage}),
})
},
}
nuxt.vueApp.use(VueQueryPlugin, options)
if (process.server) {
nuxt.hooks.hook('app:rendered', () => {
vueQueryState.value = dehydrate(queryClient)
})
}
if (process.client) {
nuxt.hooks.hook('app:created', () => {
hydrate(queryClient, vueQueryState.value)
})
}
})