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
13 * `QueryClientProvider`, plus the `persistOptions` and callbacks for when
14 * restoring succeeds or fails.
15 */
16export type PersistQueryClientProviderProps = QueryClientProviderProps & {
17 persistOptions: OmitKeyof<PersistQueryClientOptions, 'queryClient'>
18 onSuccess?: () => void
19 onError?: () => void
20}
21β
22/**
23 * Provides the `QueryClient` like `QueryClientProvider`, and restores the
24 * persisted client first: while restoring, `useIsRestoring` returns `true` and
25 * queries wait for the restore to finish before subscribing. Once restored, the
26 * client is saved with the persister whenever the cache changes.
27 *
28 * @param props - The `QueryClientProvider` props, the `persistOptions`, and the
29 * `onSuccess` and `onError` callbacks. `onSuccess` is called once restoring
30 * finishes, even if nothing was restored (e.g. because the persisted client
31 * expired), and `onError` if restoring or `onSuccess` throws.
32 * @returns The `QueryClientProvider` wrapping the children.
33 */
34export const PersistQueryClientProvider = (
35 props: PersistQueryClientProviderProps,
36): JSX.Element => {
37 const [isRestoring, setIsRestoring] = createSignal(true)
38β
39 const options = createMemo(() => ({
40 ...props.persistOptions,
41 queryClient: props.client,
42 }))
43β
44 createEffect(() => {
45 setIsRestoring(true)
46 persistQueryClientRestore(options())
47 .then(() => props.onSuccess?.())
48 .catch(() => props.onError?.())
49 .finally(() => {
50 setIsRestoring(false)
51 })
52 })
53β
54 createEffect(() => {
55 let unsubscribe = () => {}
56 if (!isRestoring()) {
57 unsubscribe = persistQueryClientSubscribe(options())
58 }
59 onCleanup(() => unsubscribe())
60 })
61β
62 return (
63 <QueryClientProvider client={props.client}>
64 <IsRestoringProvider value={isRestoring}>
65 {props.children}
66 </IsRestoringProvider>
67 </QueryClientProvider>
68 )
69}