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

useIsFetching.svelte.ts

56 lines1.8 KB

1import { ReactiveValue } from './containers.svelte.js'
2import { useQueryClient } from './useQueryClient.js'
3import type { QueryClient, QueryFilters } from '@tanstack/query-core'
4​
5/**
6 * The `useIsFetching` function returns the `number` of the queries that your
7 * application is loading or fetching in the background (useful for app-wide
8 * loading indicators).
9 *
10 * @example
11 * ;```svelte
12 * <script lang="ts">
13 * import { useIsFetching } from '@tanstack/svelte-query'
14 *
15 * // How many queries matching the posts prefix are fetching?
16 * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
17 * </script>
18 *
19 * {#if isFetchingPosts.current}
20 * <span>Refreshing posts...</span>
21 * {/if}
22 * ```
23 *
24 * @example
25 * A global loading indicator for any query fetching in the background, not just the ones on screen:
26 * ```svelte
27 * <script lang="ts">
28 * import { useIsFetching } from '@tanstack/svelte-query'
29 *
30 * const isFetching = useIsFetching()
31 * </script>
32 *
33 * {#if isFetching.current}
34 * <div>Queries are fetching in the background...</div>
35 * {/if}
36 * ```
37 *
38 * @param filters - {@link QueryFilters} to narrow down which queries to count.
39 * Omit to count every fetching query.
40 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the
41 * one from the nearest context will be used.
42 * @returns A reactive value β€” read `.current` to get how many matching queries
43 * are currently fetching.
44 */
45export function useIsFetching(
46 filters?: QueryFilters,
47 queryClient?: QueryClient,
48): ReactiveValue<number> {
49 const client = useQueryClient(queryClient)
50 const queryCache = client.getQueryCache()
51​
52 return new ReactiveValue(
53 () => client.isFetching(filters),
54 (update) => queryCache.subscribe(update),
55 )