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

useMutationState.svelte.ts

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