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