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

useIsFetching.svelte.ts

51 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 * @param filters - {@link QueryFilters} to narrow down which queries to count. Omit to count every fetching
9 * query.
10 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
11 * be used.
12 * @returns A reactive value β€” read `.current` to get how many matching queries are currently fetching.
13 * @example
14 * ```svelte
15 * <script lang="ts">
16 * import { useIsFetching } from '@tanstack/svelte-query'
17 *
18 * // How many queries matching the posts prefix are fetching?
19 * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
20 * </script>
21 *
22 * {#if isFetchingPosts.current}
23 * <span>Refreshing posts...</span>
24 * {/if}
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?: Omit<QueryFilters, 'fetchStatus'>,
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 )