-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathuseMutationState.ts
88 lines (77 loc) · 2.3 KB
/
useMutationState.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import {
computed,
getCurrentScope,
onScopeDispose,
shallowReadonly,
shallowRef,
watch,
} from 'vue-demi'
import { useQueryClient } from './useQueryClient'
import { cloneDeepUnref } from './utils'
import type { Ref } from 'vue-demi'
import type {
MutationFilters as MF,
Mutation,
MutationState,
} from '@tanstack/query-core'
import type { QueryClient } from './queryClient'
import type { MaybeRefDeep } from './types'
import type { MutationCache } from './mutationCache'
export type MutationFilters = MaybeRefDeep<MF>
export function useIsMutating(
filters: MutationFilters = {},
queryClient?: QueryClient,
): Ref<number> {
if (process.env.NODE_ENV === 'development') {
if (!getCurrentScope()) {
console.warn(
'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.',
)
}
}
const client = queryClient || useQueryClient()
const mutationState = useMutationState(
{
filters: computed(() => ({
...cloneDeepUnref(filters),
status: 'pending' as const,
})),
},
client,
)
const length = computed(() => mutationState.value.length)
return length
}
export type MutationStateOptions<TResult = MutationState> = {
filters?: MutationFilters
select?: (mutation: Mutation) => TResult
}
function getResult<TResult = MutationState>(
mutationCache: MutationCache,
options: MutationStateOptions<TResult>,
): Array<TResult> {
return mutationCache
.findAll(options.filters)
.map(
(mutation): TResult =>
(options.select ? options.select(mutation) : mutation.state) as TResult,
)
}
export function useMutationState<TResult = MutationState>(
options: MutationStateOptions<TResult> = {},
queryClient?: QueryClient,
): Readonly<Ref<Array<TResult>>> {
const filters = computed(() => cloneDeepUnref(options.filters))
const mutationCache = (queryClient || useQueryClient()).getMutationCache()
const state = shallowRef(getResult(mutationCache, options))
const unsubscribe = mutationCache.subscribe(() => {
state.value = getResult(mutationCache, options)
})
watch(filters, () => {
state.value = getResult(mutationCache, options)
})
onScopeDispose(() => {
unsubscribe()
})
return shallowReadonly(state)
}