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

useIsFetching.ts

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