Open History to see the last commit
1import {
2 persistQueryClientRestore,
3 persistQueryClientSubscribe,
4} from '@tanstack/query-persist-client-core'
5import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js'
6import { IsRestoringProvider, QueryClientProvider } from '@tanstack/solid-query'
7import type { PersistQueryClientOptions } from '@tanstack/query-persist-client-core'
8import type { OmitKeyof, QueryClientProviderProps } from '@tanstack/solid-query'
9import type { JSX } from 'solid-js'
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?: () => void
18 onError?: () => void
19}
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 props: PersistQueryClientProviderProps,
33): JSX.Element => {
34 const [isRestoring, setIsRestoring] = createSignal(true)
35β
36 const options = createMemo(() => ({
37 ...props.persistOptions,
38 queryClient: props.client,
39 }))
40β
41 createEffect(() => {
42 setIsRestoring(true)
43 persistQueryClientRestore(options())
44 .then(() => props.onSuccess?.())
45 .catch(() => props.onError?.())
46 .finally(() => {
47 setIsRestoring(false)
48 })
49 })
50β
51 createEffect(() => {
52 let unsubscribe = () => {}
53 if (!isRestoring()) {
54 unsubscribe = persistQueryClientSubscribe(options())
55 }
56 onCleanup(() => unsubscribe())
57 })
58β
59 return (
60 <QueryClientProvider client={props.client}>
61 <IsRestoringProvider value={isRestoring}>
62 {props.children}
63 </IsRestoringProvider>
64 </QueryClientProvider>
65 )
66}