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

PersistQueryClientProvider.tsx

75 lines2.6 KB

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