Open History to see the last commit
1import { getContext, setContext } from 'svelte'
2import type { QueryClient } from '@tanstack/query-core'
3import type { Box } from './containers.svelte'
4β
5const _contextKey = Symbol('QueryClient')
6β
7/**
8 * Retrieves the `QueryClient` set on Svelte's context by `QueryClientProvider`
9 * (or by {@link setQueryClientContext} directly). This is what
10 * {@link useQueryClient} calls internally.
11 *
12 * @returns The `QueryClient` set on context, whether by `QueryClientProvider`
13 * or {@link setQueryClientContext}.
14 * @throws {Error} If no `QueryClient` was found in context.
15 */
16export const getQueryClientContext = (): QueryClient => {
17 const client = getContext<QueryClient | undefined>(_contextKey)
18 if (!client) {
19 throw new Error(
20 'No QueryClient was found in Svelte context. Did you forget to wrap your component with QueryClientProvider?',
21 )
22 }
23β
24 return client
25}
26β
27/**
28 * Sets a `QueryClient` on Svelte's context, so it can be read with
29 * {@link getQueryClientContext} (or {@link useQueryClient}) from any descendant
30 * component. `QueryClientProvider` wraps this β use it directly only if you
31 * need to set the client from your own component instead.
32 *
33 * @example
34 * ;```svelte
35 * <script lang="ts">
36 * import { QueryClient, QueryClientProvider } from '@tanstack/svelte-query'
37 *
38 * const queryClient = new QueryClient()
39 * </script>
40 *
41 * <QueryClientProvider client={queryClient}>
42 * ...
43 * </QueryClientProvider>
44 * ```
45 *
46 * @param client - The `QueryClient` to make available to descendant components.
47 */
48export const setQueryClientContext = (client: QueryClient): void => {
49 setContext(_contextKey, client)
50}
51β
52const _isRestoringContextKey = Symbol('isRestoring')
53β
54/**
55 * Retrieves a `isRestoring` from Svelte's context.
56 *
57 * @returns The `isRestoring` box set on context, or a box holding `false` if
58 * none was set or the context is unavailable.
59 */
60export const getIsRestoringContext = (): Box<boolean> => {
61 try {
62 const isRestoring = getContext<Box<boolean> | undefined>(
63 _isRestoringContextKey,
64 )
65 return isRestoring ?? { current: false }
66 } catch (error) {
67 return { current: false }
68 }
69}
70β
71/**
72 * Sets a `isRestoring` on Svelte's context.
73 *
74 * @param isRestoring - The box holding whether the cache is being restored,
75 * e.g. by a persister.
76 */
77export const setIsRestoringContext = (isRestoring: Box<boolean>): void => {
78 setContext(_isRestoringContextKey, isRestoring)
79}