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

useIsFetching.ts

48 lines1.8 KB

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