TanStackT
TanStack9mo ago
18 replies
standard-azure

Cached local storage query persist

I am fetching relatively static data from an API that i dont want to spam but may update occasionally.
i never watch to refetch within a particular session and i only want to fetch upon page load, but also not more often than X hours. if i just visit the page for the first time, it should fetch. but then if i refresh the page a minute later, it should not refetch and just load from cache instead. if i wait say 12 hours and refresh, then it should fetch again and update the local storage.

I have the following basic code and the above functionality is not working. The issue is that it refetches upon page load every time.

my understanding is that the config i pass to QueryClient default options prevents all reloading during a session, and the persistOptions passed to PersistQueryClientProvider should ensure that it loads from cache until maxAge has passed upon which itll refetch from the API. What am i missing here?
const localStoragePersister = createSyncStoragePersister({
  storage: window.localStorage,
})

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      // never refetch data during a particular session
      staleTime: Infinity,
      gcTime: Infinity,
      retry: false,
      refetchOnWindowFocus: false,
      refetchOnMount: false,
      refetchOnReconnect: false,
    },
  },
})

// Render the app
const rootElement = document.getElementById('app')
if (rootElement && !rootElement.innerHTML) {
  const root = ReactDOM.createRoot(rootElement)
  root.render(
    <StrictMode>
      <PersistQueryClientProvider
        client={queryClient}
        // only refetch data upon page load if the data is old enough
        persistOptions={{
          persister: localStoragePersister,
          maxAge: 3600,
        }}
      >
        <RouterProvider router={router} />
      </PersistQueryClientProvider>
    </StrictMode>,
  )
}
Was this page helpful?