How to use persistQueryClient in react-query?
P粉908643611
P粉908643611 2023-07-27 17:13:29
0
1
509
<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粉908643611
P粉908643611

reply all(1)
P粉176980522

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>
) 
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!