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 { IsRestoringContext, 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 '@solidjs/web'
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 let didRestore = false
36β
37 const options = createMemo(() => ({
38 ...props.persistOptions,
39 queryClient: props.client,
40 }))
41β
42 createEffect(
43 () => {
44 const opts = options()
45 if (!didRestore) {
46 didRestore = true
47 persistQueryClientRestore(opts)
48 .then(() => props.onSuccess?.())
49 .catch(() => props.onError?.())
50 .finally(() => {
51 setIsRestoring(false)
52 })
53 }
54 },
55 () => {},
56 )
57β
58 createEffect(
59 () => {
60 let unsubscribe = () => {}
61 if (!isRestoring()) {
62 unsubscribe = persistQueryClientSubscribe(options())
63 }
64 onCleanup(() => unsubscribe())
65 },
66 () => {},
67 )
68β
69 return (
70 <QueryClientProvider client={props.client}>
71 <IsRestoringContext value={isRestoring}>
72 {props.children}
73 </IsRestoringContext>
74 </QueryClientProvider>
75 )
76}