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

useMutationState.svelte.ts

137 lines4.2 KB

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