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

useMutationState.ts

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