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