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