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

useIsFetching.ts

60 lines1.9 KB

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