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>
)