Add meta
to hydrated queries and mutations
#5202
-
Hi 👋 , To granularly hydrate queries (SSR and LocalStorage), we use the const queryClient = new QueryClient({
queryCache,
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 2,
meta: {
// By default we don't want to hydrate queries
hydrate: false,
},
},
},
});
// Later on somewhere in SSR land
const dehydratedState = JSON.parse(
JSON.stringify(
dehydrate(queryClient, {
shouldDehydrateQuery: ({ meta }) => !!meta?.dehydrate,
}),
),
)
// Somewhere in prefetch SSR land
queryClient.prefetch({
queryFn: () => ...,
queryKey: ['key'],
// Here comes the magic
meta: { dehydrate: true },
}) This system works wonderfully but I notice that when we want to apply this to localStorage (which also uses the const queryClient = new QueryClient({
queryCache,
defaultOptions: {
queries: {
// Set cacheTime to 24h for persisted Cache
cacheTime: 1000 * 60 * 60 * 24,
refetchOnWindowFocus: false,
retry: 2,
meta: {
// By default we don't want to store queries in local storage
localStorage: false,
},
},
},
});
const PersistOptions: PersistQueryClientProviderProps['persistOptions'] = {
persister: LocalStoragePersistor,
// Keep persisted cache for 12 hours
maxAge: 1000 * 60 * 60 * 12,
dehydrateOptions: {
shouldDehydrateQuery: query => !!query.meta?.localStorage,
},
}; What happens is the following:
The solution seems trivial (but implications might not be) that I've created a POC implementation with some tests on how to approach this https://github.com/TanStack/query/compare/main...JanStevens:query:feat/hydrate-query-meta?expand=1 WDYT? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
while it looks like a good idea, the problem is that What you can do though is provide
so that the same defaultOptions will be picked up during hydration. |
Beta Was this translation helpful? Give feedback.
while it looks like a good idea, the problem is that
meta
is an option, and not part of thestate
. We don't persist options, only state :)meta
can also easily contain non-serializable things like functions.What you can do though is provide
defaultOptions
to the hydration process: