Open History to see the last commit
1import { createEffect, createMemo, createSignal, onCleanup } from 'solid-js'
2import { useQueryClientResolver } from './QueryClientProvider'
3import type { QueryFilters } from '@tanstack/query-core'
4import type { QueryClient } from './QueryClient'
5import type { Accessor } from 'solid-js'
6β
7/**
8 * The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching
9 * in the background (useful for app-wide loading indicators).
10 *
11 * @param filters - An accessor returning the {@link QueryFilters} to narrow down the matched queries.
12 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
13 * will be used.
14 * @returns An accessor for the `number` of the queries that your application is currently loading or fetching
15 * in the background.
16 *
17 * @example
18 * ```tsx
19 * import { useIsFetching } from '@tanstack/solid-query'
20 *
21 * function GlobalLoadingIndicator() {
22 * // How many queries matching the posts prefix are fetching?
23 * const isFetchingPosts = useIsFetching(() => ({ queryKey: ['posts'] }))
24 *
25 * return isFetchingPosts() > 0 ? <span>Loading posts...</span> : null
26 * }
27 * ```
28 */
29export function useIsFetching(
30 filters?: Accessor<QueryFilters>,
31 queryClient?: Accessor<QueryClient>,
32): Accessor<number> {
33 const resolveClient = useQueryClientResolver(queryClient)
34 const client = createMemo(() => resolveClient())
35 const queryCache = createMemo(() => client().getQueryCache())
36β
37 const [fetches, setFetches] = createSignal(client().isFetching(filters?.()))
38β
39 createEffect(() => {
40 setFetches(client().isFetching(filters?.()))
41β
42 const unsubscribe = queryCache().subscribe(() => {
43 setFetches(client().isFetching(filters?.()))
44 })
45β
46 onCleanup(unsubscribe)
47 })
48β
49 return fetches
50}