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

useIsFetching.ts

73 lines1.9 KB

1import {
2 computed,
3 getCurrentScope,
4 onScopeDispose,
5 ref,
6 unref,
7 watchEffect,
8} from 'vue-demi'
9import { useQueryClient } from './useQueryClient'
10import { cloneDeepUnref, isQueryKey } from './utils'
11import type { Ref } from 'vue-demi'
12import type { QueryFilters as QF, QueryKey } from '@tanstack/query-core'
13​
14import type { MaybeRef, MaybeRefDeep, WithQueryClientKey } from './types'
15​
16export type QueryFilters = MaybeRefDeep<WithQueryClientKey<QF>>
17​
18export function useIsFetching(filters?: QueryFilters): Ref<number>
19export function useIsFetching(
20 queryKey?: MaybeRef<QueryKey>,
21 filters?: Omit<QueryFilters, 'queryKey'>,
22): Ref<number>
23export function useIsFetching(
24 arg1?: MaybeRef<QueryKey> | QueryFilters,
25 arg2?: Omit<QueryFilters, 'queryKey'>,
26): Ref<number> {
27 if (process.env.NODE_ENV === 'development') {
28 if (!getCurrentScope()) {
29 console.warn(
30 'vue-query composables like "useQuery()" should only be used inside a "setup()" function or a running effect scope. They might otherwise lead to memory leaks.',
31 )
32 }
33 }
34​
35 const filters = computed(() => parseFilterArgs(arg1, arg2))
36 const queryClient =
37 filters.value.queryClient ?? useQueryClient(filters.value.queryClientKey)
38​
39 const isFetching = ref()
40​
41 const listener = () => {
42 isFetching.value = queryClient.isFetching(filters)
43 }
44​
45 const unsubscribe = queryClient.getQueryCache().subscribe(listener)
46​
47 watchEffect(listener)
48​
49 onScopeDispose(() => {
50 unsubscribe()
51 })
52​
53 return isFetching
55​
56export function parseFilterArgs(
57 arg1?: MaybeRef<QueryKey> | QueryFilters,
58 arg2: QueryFilters = {},
59) {
60 const plainArg1 = unref(arg1)
61 const plainArg2 = unref(arg2)
62​
63 let options = plainArg1
64​
65 if (isQueryKey(plainArg1)) {
66 options = { ...plainArg2, queryKey: plainArg1 }
67 } else {
68 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
69 options = plainArg1 || {}
70 }
71​
72 return cloneDeepUnref(options) as WithQueryClientKey<QF>