I want to use two query clients: normal one for usual use cases, and persistent one to cache some queries for a long time. What is the correct implementation? Is below correct? How to use persistent query provider for certain queries? I guess by default useQuery uses the provider from the nearest content (not persistent one in my case).
'use client';
import { TooltipProvider } from '@/components/ui/tooltip';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from 'next-themes';
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister';
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client';
export const persistQueryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false,
refetchOnWindowFocus: false,
cacheTime: 1000 * 60 * 60 * 24, // 24 hours,
staleTime: 1000 * 60 * 60 * 1, // 1 hour
},
},
});
export const persister = createSyncStoragePersister({
storage: window.localStorage,
});
export const queryClient = new QueryClient();
export default function GlobalProviders({
children,
}: {
children: React.ReactNode;
}) {
return (
<ThemeProvider
attribute='class'
defaultTheme='system'
enableSystem
disableTransitionOnChange
>
<PersistQueryClientProvider
client={persistQueryClient}
persistOptions={{ persister }}
>
<QueryClientProvider client={queryClient}>
<TooltipProvider>{children}</TooltipProvider>
</QueryClientProvider>
</PersistQueryClientProvider>
</ThemeProvider>
);
}
Also, for each query I want to specify cache time separately as below where the query should be stale after midnight:
return useQuery(['usersStats'], queryFn, {
cacheTime: new Date().setHours(24, 0, 0, 0) - Date.now(),
});