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

PersistQueryClientProvider.tsx

68 lines2.6 KB

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