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