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