英文:
How does the persistQueryClient from react-query work?
问题
我正在使用React Query进行API调用,但当我重新加载页面时,状态会丢失。我在StackOverflow上发布了一个问题,询问是否有办法在react-query中持久化数据,然后有人回答说可以使用persistQueryClient,但我尝试阅读文档后仍然不明白它是如何工作的。有人可以请解释一下吗?
https://tanstack.com/query/v4/docs/react/plugins/persistQueryClient
英文:
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
答案1
得分: 2
persistQueryClient
是标准queryClient
的一个包装器,用于将缓存持久化到某种形式的存储,例如localStorage。
要定义和使用persistQueryClient
,我们需要:
- 创建一个具有较长缓存时间的查询客户端。
- 创建一个持久化器。
- 将查询客户端和持久化器都包装在
persistQueryClient
中。
文档提供的示例:
import { PersistQueryClientProvider } from '@tanstack/react-query-persist-client'
import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'
// 1. 查询客户端
const queryClient = new QueryClient({
defaultOptions: {
queries: {
cacheTime: 1000 * 60 * 60 * 24, // 24小时
},
},
})
// 2. 持久化器
const persister = createSyncStoragePersister({
storage: window.localStorage,
})
// 3. 使用<PersistQueryClientProvider>替换<QueryClientProvider>
ReactDOM.createRoot(rootElement).render(
<PersistQueryClientProvider
client={queryClient}
persistOptions={{ persister }}
>
<App />
</PersistQueryClientProvider>
)
英文:
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:
- Create a query client with a large cache time.
- Create a persister
- Wrap both the query client and persister in a
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>
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论