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

PersistQueryClientProvider.tsx

61 lines1.8 KB

1import { useEffect, useRef, useState } from 'preact/hooks'
2import type { VNode } from 'preact'
3​
4import {
5 persistQueryClientRestore,
6 persistQueryClientSubscribe,
7} from '@tanstack/query-persist-client-core'
8import {
9 IsRestoringProvider,
10 QueryClientProvider,
11} from '@tanstack/preact-query'
12import type { PersistQueryClientOptions } from '@tanstack/query-persist-client-core'
13import type {
14 OmitKeyof,
15 QueryClientProviderProps,
16} from '@tanstack/preact-query'
17​
18export type PersistQueryClientProviderProps = QueryClientProviderProps & {
19 persistOptions: OmitKeyof<PersistQueryClientOptions, 'queryClient'>
20 onSuccess?: () => Promise<unknown> | unknown
21 onError?: () => Promise<unknown> | unknown
23​
24export const PersistQueryClientProvider = ({
25 children,
26 persistOptions,
27 onSuccess,
28 onError,
29 ...props
30}: PersistQueryClientProviderProps): VNode => {
31 const [isRestoring, setIsRestoring] = useState(true)
32 const optionsRef = useRef({ persistOptions, onSuccess, onError })
33 const didRestoreRef = useRef(false)
34​
35 useEffect(() => {
36 optionsRef.current = { persistOptions, onSuccess, onError }
37 })
38​
39 useEffect(() => {
40 const options = {
41 ...optionsRef.current.persistOptions,
42 queryClient: props.client,
43 }
44 if (!didRestoreRef.current) {
45 didRestoreRef.current = true
46 persistQueryClientRestore(options)
47 .then(() => optionsRef.current.onSuccess?.())
48 .catch(() => optionsRef.current.onError?.())
49 .finally(() => {
50 setIsRestoring(false)
51 })
52 }
53 return isRestoring ? undefined : persistQueryClientSubscribe(options)
54 }, [props.client, isRestoring])
55​
56 return (
57 <QueryClientProvider {...props}>
58 <IsRestoringProvider value={isRestoring}>{children}</IsRestoringProvider>
59 </QueryClientProvider>
60 )