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