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

useIsFetching.svelte.ts

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