Open History to see the last commit
1import { getCurrentScope, onScopeDispose, ref, watchEffect } from 'vue-demi'
2import { useQueryClient } from './useQueryClient'
3import { cloneDeepUnref } from './utils'
4import type { Ref } from 'vue-demi'
5import type { QueryFilters } from '@tanstack/query-core'
6import type { MaybeRefDeep } from './types'
7import type { QueryClient } from './queryClient'
8β
9export type UseIsFetchingFilters =
10 | MaybeRefDeep<QueryFilters>
11 | (() => MaybeRefDeep<QueryFilters>)
12β
13/**
14 * The `useIsFetching` composable returns a `ref` to the `number` of the queries that your application is
15 * loading or fetching in the background (useful for app-wide loading indicators).
16 *
17 * `fetchingFilters` may be a plain object, `MaybeRefDeep`, or a reactive getter (`() => ({ ... })`) β pass a
18 * getter if the filters themselves depend on other reactive state.
19 *
20 * @param fetchingFilters - The {@link QueryFilters} to narrow down the matched queries.
21 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
22 * will be used.
23 * @returns A `ref` to the `number` of the queries that your application is currently loading or fetching in
24 * the background.
25 *
26 * @example
27 * ```vue
28 * <script setup lang="ts">
29 * import { useIsFetching } from '@tanstack/vue-query'
30 *
31 * // How many queries matching the posts prefix are fetching?
32 * const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
33 * </script>
34 *
35 * <template>
36 * <span v-if="isFetchingPosts">Refreshing posts...</span>
37 * </template>
38 * ```
39 *
40 * @example
41 * A global loading indicator for any query fetching in the background, not just the ones on screen:
42 * ```vue
43 * <script setup lang="ts">
44 * import { useIsFetching } from '@tanstack/vue-query'
45 *
46 * const isFetching = useIsFetching()
47 * </script>
48 *
49 * <template>
50 * <div v-if="isFetching">Queries are fetching in the background...</div>
51 * </template>
52 * ```
53 */
54export function useIsFetching(
55 fetchingFilters: UseIsFetchingFilters = {},
56 queryClient?: QueryClient,
57): Ref<number> {
58 if (process.env.NODE_ENV === 'development') {
59 if (!getCurrentScope()) {
60 console.warn(
61 'vue-query composable like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
62 )
63 }
64 }
65β
66 const client = queryClient || useQueryClient()
67β
68 const isFetching = ref()
69β
70 const listener = () => {
71 const resolvedFilters =
72 typeof fetchingFilters === 'function'
73 ? fetchingFilters()
74 : fetchingFilters
75 isFetching.value = client.isFetching(cloneDeepUnref(resolvedFilters))
76 }
77β
78 const unsubscribe = client.getQueryCache().subscribe(listener)
79β
80 watchEffect(listener)
81β
82 onScopeDispose(() => {
83 unsubscribe()
84 })
85β
86 return isFetching
87}