How to run query once a day using `tanstack-query`

12 Views Asked by At

I want to run a query only once a day (every midnight) to count a number of users registered during last 24hours. I know that I can do this with persistQueryClient which saves the results to localStorage. However, I don't know how to combine it with normal queryClient in such a way that only selected queries uses persist query client. Below code never uses persist client, and if I swap provider with each other, then always persist one will be used. How to combine them?

'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>
  );
}

0

There are 0 best solutions below