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

useIsFetching.ts

38 lines1.5 KB

1import { createMemo } from 'solid-js'
2import { createCacheAggregate } from './cacheAggregate'
3import { useQueryClient } from './QueryClientProvider'
4import type { QueryFilters } from '@tanstack/query-core'
5import type { QueryClient } from './QueryClient'
6import type { Accessor } from 'solid-js'
7​
8/**
9 * The `useIsFetching` primitive returns the `number` of the queries that your application is loading or fetching
10 * in the background (useful for app-wide loading indicators).
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 * @example
17 * ```tsx
18 * import { useIsFetching } from '@tanstack/solid-query'
19 *
20 * function GlobalLoadingIndicator() {
21 * // How many queries matching the posts prefix are fetching?
22 * const isFetchingPosts = useIsFetching(() => ({ queryKey: ['posts'] }))
23 *
24 * return isFetchingPosts() > 0 ? <span>Loading posts...</span> : null
25 * }
26 * ```
27 */
28export function useIsFetching(
29 filters?: Accessor<Omit<QueryFilters, 'fetchStatus'>>,
30 queryClient?: Accessor<QueryClient>,
31): Accessor<number> {
32 const client = createMemo(() => useQueryClient(queryClient?.()))
33 return createCacheAggregate(
34 (onEvent) => client().getQueryCache().subscribe(onEvent),
35 () => client().isFetching(filters?.()),
36 0,
37 )