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

useIsFetching.ts

59 lines1.5 KB

1import { onScopeDispose, ref, watch } from 'vue-demi'
2import type { Ref } from 'vue-demi'
3import type { QueryKey, QueryFilters as QF } from '@tanstack/query-core'
4​
5import { useQueryClient } from './useQueryClient'
6import { cloneDeepUnref, isQueryKey } from './utils'
7import type { MaybeRefDeep, WithQueryClientKey } from './types'
8​
9export type QueryFilters = MaybeRefDeep<WithQueryClientKey<QF>>
10​
11export function useIsFetching(filters?: QueryFilters): Ref<number>
12export function useIsFetching(
13 queryKey?: QueryKey,
14 filters?: QueryFilters,
15): Ref<number>
16export function useIsFetching(
17 arg1?: QueryKey | QueryFilters,
18 arg2?: QueryFilters,
19): Ref<number> {
20 const filters = ref(parseFilterArgs(arg1, arg2))
21 const queryClient =
22 filters.value.queryClient ?? useQueryClient(filters.value.queryClientKey)
23​
24 const isFetching = ref(queryClient.isFetching(filters))
25​
26 const unsubscribe = queryClient.getQueryCache().subscribe(() => {
27 isFetching.value = queryClient.isFetching(filters)
28 })
29​
30 watch(
31 [() => arg1, () => arg2],
32 () => {
33 filters.value = parseFilterArgs(arg1, arg2)
34 isFetching.value = queryClient.isFetching(filters)
35 },
36 { deep: true },
37 )
38​
39 onScopeDispose(() => {
40 unsubscribe()
41 })
42​
43 return isFetching
45​
46export function parseFilterArgs(
47 arg1?: QueryKey | QueryFilters,
48 arg2: QueryFilters = {},
49) {
50 let options: QueryFilters
51​
52 if (isQueryKey(arg1)) {
53 options = { ...arg2, queryKey: arg1 }
54 } else {
55 options = arg1 || {}
56 }
57​
58 return cloneDeepUnref(options) as WithQueryClientKey<QF>