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

useMutationState.svelte.ts

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