Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

PersistQueryClientProvider.tsx

72 lines2.6 KB

1'use client'
2import * as React from 'react'
3​
4import {
5 persistQueryClientRestore,
6 persistQueryClientSubscribe,
7} from '@tanstack/query-persist-client-core'
8import { IsRestoringProvider, QueryClientProvider } from '@tanstack/react-query'
9import type { PersistQueryClientOptions } from '@tanstack/query-persist-client-core'
10import type { OmitKeyof, QueryClientProviderProps } from '@tanstack/react-query'
11​
12/**
13 * The props of `PersistQueryClientProvider`: the props of
14 * `QueryClientProvider`, plus the `persistOptions` and callbacks for when
15 * restoring succeeds or fails.
16 */
17export type PersistQueryClientProviderProps = QueryClientProviderProps & {
18 persistOptions: OmitKeyof<PersistQueryClientOptions, 'queryClient'>
19 onSuccess?: () => Promise<unknown> | unknown
20 onError?: () => Promise<unknown> | unknown
22​
23/**
24 * Provides the `QueryClient` like `QueryClientProvider`, and restores the
25 * persisted client first: while restoring, `useIsRestoring` returns `true` and
26 * queries wait for the restore to finish before subscribing. Once restored, the
27 * client is saved with the persister whenever the cache changes.
28 *
29 * @param props - The `QueryClientProvider` props, the `persistOptions`, and the
30 * `onSuccess` and `onError` callbacks. `onSuccess` is called once restoring
31 * finishes, even if nothing was restored (e.g. because the persisted client
32 * expired), and `onError` if restoring or `onSuccess` throws.
33 * @returns The `QueryClientProvider` wrapping the children.
34 */
35export const PersistQueryClientProvider = ({
36 children,
37 persistOptions,
38 onSuccess,
39 onError,
40 ...props
41}: PersistQueryClientProviderProps): React.JSX.Element => {
42 const [isRestoring, setIsRestoring] = React.useState(true)
43 const optionsRef = React.useRef({ persistOptions, onSuccess, onError })
44 const didRestoreRef = React.useRef(false)
45​
46 React.useEffect(() => {
47 optionsRef.current = { persistOptions, onSuccess, onError }
48 })
49​
50 React.useEffect(() => {
51 const options = {
52 ...optionsRef.current.persistOptions,
53 queryClient: props.client,
54 }
55 if (!didRestoreRef.current) {
56 didRestoreRef.current = true
57 persistQueryClientRestore(options)
58 .then(() => optionsRef.current.onSuccess?.())
59 .catch(() => optionsRef.current.onError?.())
60 .finally(() => {
61 setIsRestoring(false)
62 })
63 }
64 return isRestoring ? undefined : persistQueryClientSubscribe(options)
65 }, [props.client, isRestoring])
66​
67 return (
68 <QueryClientProvider {...props}>
69 <IsRestoringProvider value={isRestoring}>{children}</IsRestoringProvider>
70 </QueryClientProvider>
71 )