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

PersistQueryClientProvider.svelte

56 lines1.3 KB

1<script lang="ts">
2 import {
3 persistQueryClientRestore,
4 persistQueryClientSubscribe,
5 } from '@tanstack/query-persist-client-core'
6 import {
7 QueryClientProvider,
8 setIsRestoringContext,
9 } from '@tanstack/svelte-query'
10 import { box } from './utils.svelte.js'
11 import type { PersistQueryClientOptions } from '@tanstack/query-persist-client-core'
12 import type {
13 OmitKeyof,
14 QueryClientProviderProps,
15 } from '@tanstack/svelte-query'
16​
17 type PersistQueryClientProviderProps = QueryClientProviderProps & {
18 persistOptions: OmitKeyof<PersistQueryClientOptions, 'queryClient'>
19 onSuccess?: () => void
20 onError?: () => void
21 }
22​
23 let {
24 client,
25 children,
26 persistOptions,
27 ...props
28 }: PersistQueryClientProviderProps = $props()
29​
30 let isRestoring = box(true)
31​
32 setIsRestoringContext(isRestoring)
33​
34 const options = $derived({
35 ...persistOptions,
36 queryClient: client,
37 })
38​
39 $effect(() => {
40 return isRestoring.current ? () => {} : persistQueryClientSubscribe(options)
41 })
42​
43 $effect(() => {
44 isRestoring.current = true
45 persistQueryClientRestore(options)
46 .then(() => props.onSuccess?.())
47 .catch(() => props.onError?.())
48 .finally(() => {
49 isRestoring.current = false
50 })
51 })
52</script>
53​
54<QueryClientProvider {client} {...props}>
55 {@render children()}
56</QueryClientProvider>