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