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

useMutationState.ts

89 lines2.3 KB

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