Open History to see the last commit
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 Mutation,
14 MutationFilters,
15 MutationState,
16} from '@tanstack/query-core'
17import type { QueryClient } from './queryClient'
18import type { MaybeRefDeep } from './types'
19import type { MutationCache } from './mutationCache'
20β
21type VueMutationFilters = MaybeRefDeep<MutationFilters>
22β
23export type UseIsMutatingFilters =
24 | VueMutationFilters
25 | (() => VueMutationFilters)
26β
27/**
28 * The `useIsMutating` composable returns a `ref` to the `number` of mutations that your application currently
29 * has `pending` (useful for app-wide loading indicators).
30 *
31 * `filters` may be a plain object, `MaybeRefDeep`, or a reactive getter (`() => ({ ... })`) β pass a getter if
32 * the filters themselves depend on other reactive state.
33 *
34 * @param filters - The {@link MutationFilters} to narrow down the matched mutations.
35 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
36 * will be used.
37 * @returns A `ref` to the `number` of the mutations that your application currently has `pending`.
38 *
39 * @example
40 * ```vue
41 * <script setup lang="ts">
42 * import { useIsMutating } from '@tanstack/vue-query'
43 *
44 * // How many mutations matching the posts prefix are in progress?
45 * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
46 * </script>
47 *
48 * <template>
49 * <span v-if="isMutatingPosts">Saving posts...</span>
50 * </template>
51 * ```
52 */
53export function useIsMutating(
54 filters: UseIsMutatingFilters = {},
55 queryClient?: QueryClient,
56): Ref<number> {
57 if (process.env.NODE_ENV === 'development') {
58 if (!getCurrentScope()) {
59 console.warn(
60 '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.',
61 )
62 }
63 }
64β
65 const client = queryClient || useQueryClient()
66β
67 const mutationState = useMutationState(
68 {
69 filters: computed(() => ({
70 ...cloneDeepUnref(typeof filters === 'function' ? filters() : filters),
71 status: 'pending' as const,
72 })),
73 },
74 client,
75 )
76 const length = computed(() => mutationState.value.length)
77β
78 return length
79}
80β
81type MutationTypeFromResult<TResult> = [TResult] extends [
82 MutationState<
83 infer TData,
84 infer TError,
85 infer TVariables,
86 infer TOnMutateResult
87 >,
88]
89 ? Mutation<TData, TError, TVariables, TOnMutateResult>
90 : Mutation
91β
92export type MutationStateOptions<
93 TResult = MutationState,
94 TMutation extends Mutation<any, any, any, any> =
95 MutationTypeFromResult<TResult>,
96> = {
97 filters?: VueMutationFilters
98 select?: (mutation: TMutation) => TResult
99}
100β
101function getResult<
102 TResult = MutationState,
103 TMutation extends Mutation<any, any, any, any> =
104 MutationTypeFromResult<TResult>,
105>(
106 mutationCache: MutationCache,
107 options: MutationStateOptions<TResult, TMutation>,
108): Array<TResult> {
109 return mutationCache
110 .findAll(options.filters)
111 .map(
112 (mutation): TResult =>
113 (options.select
114 ? options.select(mutation as TMutation)
115 : mutation.state) as TResult,
116 )
117}
118β
119/**
120 * `useMutationState` is a composable that gives you access to all mutations in the `MutationCache`. You can
121 * pass `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the
122 * mutation state.
123 *
124 * `options` may be a plain object or a reactive getter (`() => ({ ... })`) β pass a getter if the filters
125 * themselves depend on other reactive state.
126 *
127 * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
128 * mutation state.
129 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one provided by `VueQueryPlugin`
130 * will be used.
131 * @returns A `ref` to an Array of whatever `select` returns for each matching mutation.
132 *
133 * @example
134 * Get all variables of all running mutations:
135 * ```vue
136 * <script setup lang="ts">
137 * import { useMutationState } from '@tanstack/vue-query'
138 *
139 * const pendingVariables = useMutationState({
140 * filters: { status: 'pending' },
141 * select: (mutation) => mutation.state.variables,
142 * })
143 * </script>
144 *
145 * <template>{{ pendingVariables.length }} posts saving...</template>
146 * ```
147 *
148 * @example
149 * Get all data for specific mutations via the `mutationKey`:
150 * ```vue
151 * <script setup lang="ts">
152 * import { useMutation, useMutationState } from '@tanstack/vue-query'
153 *
154 * const mutationKey = ['posts']
155 *
156 * // Some mutation that we want to get the state for
157 * const mutation = useMutation({
158 * mutationKey,
159 * mutationFn: createPosts,
160 * })
161 *
162 * const savedPosts = useMutationState({
163 * // this mutation key needs to match the mutation key of the given mutation (see above)
164 * filters: { mutationKey, status: 'success' },
165 * select: (mutation) => mutation.state.data,
166 * })
167 * </script>
168 *
169 * <template>
170 * <button @click="mutation.mutate(['New Post'])">
171 * Create post ({{ savedPosts.length }} saved so far)
172 * </button>
173 * </template>
174 * ```
175 *
176 * @example
177 * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
178 * entry to the mutation cache for `gcTime` milliseconds β with the `status: 'success'` filter below, check the
179 * last item that `useMutationState` returns to get the latest successful invocation:
180 * ```vue
181 * <script setup lang="ts">
182 * import { computed } from 'vue'
183 * import { useMutationState } from '@tanstack/vue-query'
184 *
185 * const savedPosts = useMutationState({
186 * filters: { mutationKey: ['posts'], status: 'success' },
187 * select: (mutation) => mutation.state.data,
188 * })
189 *
190 * const latestSavedPost = computed(() => savedPosts.value[savedPosts.value.length - 1])
191 * </script>
192 *
193 * <template>{{ latestSavedPost ? 'Saved' : 'Nothing saved yet' }}</template>
194 * ```
195 */
196export function useMutationState<
197 TResult = MutationState,
198 TMutation extends Mutation<any, any, any, any> =
199 MutationTypeFromResult<TResult>,
200>(
201 options:
202 | MutationStateOptions<TResult, TMutation>
203 | (() => MutationStateOptions<TResult, TMutation>) = {},
204 queryClient?: QueryClient,
205): Readonly<Ref<Array<TResult>>> {
206 const resolvedOptions = computed(() => {
207 const newOptions = typeof options === 'function' ? options() : options
208 return {
209 filters: cloneDeepUnref(newOptions.filters),
210 select: newOptions.select,
211 }
212 })
213 const mutationCache = (queryClient || useQueryClient()).getMutationCache()
214 const state = shallowRef(getResult(mutationCache, resolvedOptions.value))
215 const unsubscribe = mutationCache.subscribe(() => {
216 state.value = getResult(mutationCache, resolvedOptions.value)
217 })
218β
219 watch(resolvedOptions, () => {
220 state.value = getResult(mutationCache, resolvedOptions.value)
221 })
222β
223 onScopeDispose(() => {
224 unsubscribe()
225 })
226β
227 return shallowReadonly(state)
228}