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

useIsFetching.ts

85 lines2.7 KB

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