Open History to see the last commit
1import { notifyManager } from '@tanstack/query-core'
2import { useCallback } from 'preact/hooks'
3import { useQueryClient } from './QueryClientProvider'
4import { useSyncExternalStore } from './utils'
5import type { QueryClient, QueryFilters } from '@tanstack/query-core'
6β
7/**
8 * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching in
9 * the background (useful for app-wide loading indicators).
10 * @param filters - The {@link QueryFilters} to narrow down the matched queries.
11 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
12 * be used.
13 * @returns Will be the `number` of the queries that your application is currently loading or fetching in the
14 * background.
15 * @example
16 * ```tsx
17 * import { useIsFetching } from '@tanstack/preact-query'
18 *
19 * function PostsFetchingIndicator() {
20 * // How many queries matching the posts prefix are fetching?
21 * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
22 *
23 * return isFetchingPosts ? <span>Refreshing posts...</span> : null
24 * }
25 * ```
26 * @example
27 * A global loading indicator for any query fetching in the background, not just the ones on screen:
28 * ```tsx
29 * import { useIsFetching } from '@tanstack/preact-query'
30 *
31 * function GlobalLoadingIndicator() {
32 * const isFetching = useIsFetching()
33 *
34 * return isFetching ? (
35 * <div>Queries are fetching in the background...</div>
36 * ) : null
37 * }
38 * ```
39 */
40export function useIsFetching(
41 filters?: Omit<QueryFilters, 'fetchStatus'>,
42 queryClient?: QueryClient,
43): number {
44 const client = useQueryClient(queryClient)
45 const queryCache = client.getQueryCache()
46β
47 return useSyncExternalStore(
48 useCallback(
49 (onStoreChange) =>
50 queryCache.subscribe(notifyManager.batchCalls(onStoreChange)),
51 [queryCache],
52 ),
53 () => client.isFetching(filters),
54 )
55}