Open History to see the last commit
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
22}
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 refs = useRef({ persistOptions, onSuccess, onError })
33 const didRestore = useRef(false)
34β
35 useEffect(() => {
36 refs.current = { persistOptions, onSuccess, onError }
37 })
38β
39 useEffect(() => {
40 const options = {
41 ...refs.current.persistOptions,
42 queryClient: props.client,
43 }
44 if (!didRestore.current) {
45 didRestore.current = true
46 persistQueryClientRestore(options)
47 .then(() => refs.current.onSuccess?.())
48 .catch(() => refs.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 )
61}