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