Open History to see the last commit
1import { replaceEqualDeep } from '@tanstack/query-core'
2import { useQueryClient } from './useQueryClient.js'
3import type {
4 Mutation,
5 MutationCache,
6 MutationState,
7 QueryClient,
8} from '@tanstack/query-core'
9import type { MutationStateOptions, MutationTypeFromResult } from './types.js'
10β
11function getResult<
12 TResult = MutationState,
13 TMutation extends Mutation<any, any, any, any> =
14 MutationTypeFromResult<TResult>,
15>(
16 mutationCache: MutationCache,
17 options: MutationStateOptions<TResult, TMutation>,
18): Array<TResult> {
19 return mutationCache
20 .findAll(options.filters)
21 .map(
22 (mutation): TResult =>
23 (options.select
24 ? options.select(mutation as TMutation)
25 : mutation.state) as TResult,
26 )
27}
28β
29/**
30 * `useMutationState` is a function that gives you access to all mutations in the `MutationCache`. You can pass
31 * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
32 * state.
33 *
34 * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the
35 * mutation state.
36 * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will
37 * be used.
38 * @returns An Array of whatever `select` returns for each matching mutation.
39 *
40 * @example
41 * Get all variables of all running mutations:
42 * ```svelte
43 * <script lang="ts">
44 * import { useMutationState } from '@tanstack/svelte-query'
45 *
46 * const pendingVariables = useMutationState({
47 * filters: { status: 'pending' },
48 * select: (mutation) => mutation.state.variables,
49 * })
50 * </script>
51 *
52 * {pendingVariables.length} posts saving...
53 * ```
54 *
55 * @example
56 * Get all data for specific mutations via the `mutationKey`:
57 * ```svelte
58 * <script lang="ts">
59 * import { createMutation, useMutationState } from '@tanstack/svelte-query'
60 *
61 * const mutationKey = ['posts']
62 *
63 * // Some mutation that we want to get the state for
64 * const mutation = createMutation(() => ({
65 * mutationKey,
66 * mutationFn: createPosts,
67 * }))
68 *
69 * const savedPosts = useMutationState({
70 * // this mutation key needs to match the mutation key of the given mutation (see above)
71 * filters: { mutationKey, status: 'success' },
72 * select: (mutation) => mutation.state.data,
73 * })
74 * </script>
75 *
76 * <button onclick={() => mutation.mutate(['New Post'])}>
77 * Create post ({savedPosts.length} saved so far)
78 * </button>
79 * ```
80 *
81 * @example
82 * Access the latest mutation data via the `mutationKey`. Each invocation of `mutate` adds a new entry to the
83 * mutation cache for `gcTime` milliseconds β check the last item that `useMutationState` returns to get the
84 * latest successful mutation (the `status: 'success'` filter above excludes pending/errored ones):
85 * ```svelte
86 * <script lang="ts">
87 * import { useMutationState } from '@tanstack/svelte-query'
88 *
89 * const savedPosts = useMutationState({
90 * filters: { mutationKey: ['posts'], status: 'success' },
91 * select: (mutation) => mutation.state.data,
92 * })
93 *
94 * const latestSavedPost = $derived(savedPosts[savedPosts.length - 1])
95 * </script>
96 *
97 * {latestSavedPost ? 'Saved' : 'Nothing saved yet'}
98 * ```
99 */
100export function useMutationState<
101 TResult = MutationState,
102 TMutation extends Mutation<any, any, any, any> =
103 MutationTypeFromResult<TResult>,
104>(
105 options: MutationStateOptions<TResult, TMutation> = {},
106 queryClient?: QueryClient,
107): Array<TResult> {
108 const mutationCache = useQueryClient(queryClient).getMutationCache()
109 const result = $state(getResult(mutationCache, options))
110β
111 $effect(() => {
112 const unsubscribe = mutationCache.subscribe(() => {
113 const nextResult = replaceEqualDeep(
114 result,
115 getResult(mutationCache, options),
116 )
117 if (result !== nextResult) {
118 result.splice(0, result.length, ...nextResult)
119 }
120 })
121β
122 return unsubscribe
123 })
124β
125 /* $effect(() => {
126 mutationCache.subscribe(() => {
127 const nextResult = replaceEqualDeep(
128 result.current,
129 getResult(mutationCache, optionsRef),
130 )
131 if (result.current !== nextResult) {
132 result = nextResult
133 //notifyManager.schedule(onStoreChange)
134 }
135 })
136 }) */
137 return result
138}