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

useMutationState.ts

96 lines2.6 KB

1import {
2 computed,
3 getCurrentScope,
4 onScopeDispose,
5 shallowReadonly,
6 shallowRef,
7 watch,
8} from 'vue-demi'
9import { useQueryClient } from './useQueryClient'
10import { cloneDeepUnref } from './utils'
11import type { 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 | (() => 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(typeof filters === 'function' ? filters() : 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:
70 | MutationStateOptions<TResult>
71 | (() => MutationStateOptions<TResult>) = {},
72 queryClient?: QueryClient,
73): Readonly<Ref<Array<TResult>>> {
74 const resolvedOptions = computed(() => {
75 const newOptions = typeof options === 'function' ? options() : options
76 return {
77 filters: cloneDeepUnref(newOptions.filters),
78 select: newOptions.select,
79 }
80 })
81 const mutationCache = (queryClient || useQueryClient()).getMutationCache()
82 const state = shallowRef(getResult(mutationCache, resolvedOptions.value))
83 const unsubscribe = mutationCache.subscribe(() => {
84 state.value = getResult(mutationCache, resolvedOptions.value)
85 })
86​
87 watch(resolvedOptions, () => {
88 state.value = getResult(mutationCache, resolvedOptions.value)
89 })
90​
91 onScopeDispose(() => {
92 unsubscribe()
93 })
94​
95 return shallowReadonly(state)