search

Home  >  Q&A  >  body text

How to use persistQueryClient in react-query?

<p>I'm using React Query to make API calls, but when I reload the page, the state is lost. I posted a question on Stack Overflow asking if there was a way to persist data in react-query and someone answered that it could be done using persistQueryClient, but I tried reading the documentation and still don't understand how it works. Can anyone explain this? </p><p>You can refer to the following link to learn more about persistQueryClient: https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient</p><p>< ;br /></p>
P粉908643611P粉908643611484 days ago530

reply all(1)I'll reply

  • P粉176980522

    P粉1769805222023-07-28 10:23:22

    persistQueryClient is a wrapper for the standard queryClient, which persists the cache to some storage medium, such as localStorage.

    To define and persistQueryClient, we need:

    1. Create a query client with a long cache time.

    2. Create a persister.

    3. Wrap query client and persister in persistQueryClient.

    The following is an example provided by the documentation:

    import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
    import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
    
    // 1. the query client
    const queryClient = new QueryClient({
      defaultOptions: {
        queries: {
          cacheTime: 1000 * 60 * 60 * 24, // 24 hours
        },
      },
    })
    
    // 2. the persister
    const persister = createSyncStoragePersister({
      storage: window.localStorage,
    })
    
    // 3. Replace the <QueryClientProvider> with <PersistQueryClientProvider>
    ReactDOM.createRoot(rootElement).render(
      <PersistQueryClientProvider
        client={queryClient}
        persistOptions={{ persister }}
      >
        <App />
      </PersistQueryClientProvider>
    ) 

    reply
    0
  • Cancelreply