I'm using React Query to make my API calls, but when I reload the page, the state is lost. I posted a question on StackOverflow asking if there is a way to persist data in react-query then someone responded saying that there is a way to do with persistQueryClient, but I tried reading the documentation and I still don't understand how it works. Can someone please explain to me?
https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient
The persistQueryClient is a wrapper around the standard queryClient that persists the cache to some form of storage e.g localStorage.
To define and use a persistQueryClient, we'll need to:
persistQueryClient.An example provided by the docs:
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>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With