Open History to see the last commit
1import { createMemo } from 'solid-js'
2import { replaceEqualDeep } from '@tanstack/query-core'
3import { createCacheAggregate } from './cacheAggregate'
4import { useQueryClient } from './QueryClientProvider'
5import type {
6 Mutation,
7 MutationCache,
8 MutationFilters,
9 MutationState,
10} from '@tanstack/query-core'
11import type { Accessor } from 'solid-js'
12import type { QueryClient } from './QueryClient'
13β
14type MutationTypeFromResult<TResult> = [TResult] extends [
15 MutationState<
16 infer TData,
17 infer TError,
18 infer TVariables,
19 infer TOnMutateResult
20 >,
21]
22 ? Mutation<TData, TError, TVariables, TOnMutateResult>
23 : Mutation
24β
25type MutationStateOptions<
26 TResult = MutationState,
27 TMutation extends Mutation<any, any, any, any> =
28 MutationTypeFromResult<TResult>,
29> = {
30 filters?: MutationFilters
31 select?: (mutation: TMutation) => TResult
32}
33β
34/**
35 * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
36 * (or to their state, by default).
37 * @param mutationCache - The mutation cache to read.
38 * @param options - The `filters` to match and the `select` function to map each mutation with.
39 * @returns The selected value of every matching mutation.
40 */
41function getResult<
42 TResult = MutationState,
43 TMutation extends Mutation<any, any, any, any> =
44 MutationTypeFromResult<TResult>,
45>(
46 mutationCache: MutationCache,
47 options: MutationStateOptions<TResult, TMutation>,
48): Array<TResult> {
49 return mutationCache
50 .findAll(options.filters)
51 .map(
52 (mutation): TResult =>
53 (options.select
54 ? options.select(mutation as TMutation)
55 : mutation.state) as TResult,
56 )
57}
58β
59/**
60 * `useMutationState` is a primitive that gives you access to all mutations in the `MutationCache`. You can pass
61 * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
62 * state.
63 * @param options - An accessor returning the `filters` to narrow down matched mutations, and an optional
64 * `select` to transform the mutation state.
65 * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
66 * will be used.
67 * @returns An accessor for an array of whatever `select` returns for each matching mutation.
68 * @example
69 * Get all variables of all running mutations:
70 * ```tsx
71 * import { useMutationState } from '@tanstack/solid-query'
72 *
73 * function PendingPosts() {
74 * const pendingVariables = useMutationState(() => ({
75 * filters: { status: 'pending' },
76 * select: (mutation) => mutation.state.variables,
77 * }))
78 *
79 * return <>{pendingVariables().length} posts saving...</>
80 * }
81 * ```
82 * @example
83 * Get all data for specific mutations via the `mutationKey`:
84 * ```tsx
85 * import { useMutation, useMutationState } from '@tanstack/solid-query'
86 *
87 * const mutationKey = ['posts']
88 *
89 * function Posts() {
90 * // Some mutation that we want to get the state for
91 * const createPostsMutation = useMutation(() => ({
92 * mutationKey,
93 * mutationFn: createPosts,
94 * }))
95 *
96 * const savedPosts = useMutationState(() => ({
97 * // this mutation key needs to match the mutation key of the given mutation (see above)
98 * filters: { mutationKey, status: 'success' },
99 * select: (mutation) => mutation.state.data,
100 * }))
101 *
102 * return (
103 * <button onClick={() => createPostsMutation.mutate(['New Post'])}>
104 * Create post ({savedPosts().length} saved so far)
105 * </button>
106 * )
107 * }
108 * ```
109 * @example
110 * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
111 * entry to the mutation cache for `gcTime` milliseconds β with the `status: 'success'` filter below, check the
112 * last item that `useMutationState` returns to get the latest successful invocation:
113 * ```tsx
114 * import { useMutationState } from '@tanstack/solid-query'
115 *
116 * function LatestPost() {
117 * const savedPosts = useMutationState(() => ({
118 * filters: { mutationKey: ['posts'], status: 'success' },
119 * select: (mutation) => mutation.state.data,
120 * }))
121 *
122 * const latestPost = () => savedPosts()[savedPosts().length - 1]
123 *
124 * return <span>{latestPost()?.title}</span>
125 * }
126 * ```
127 */
128export function useMutationState<
129 TResult = MutationState,
130 TMutation extends Mutation<any, any, any, any> =
131 MutationTypeFromResult<TResult>,
132>(
133 options: Accessor<MutationStateOptions<TResult, TMutation>> = () => ({}),
134 queryClient?: Accessor<QueryClient>,
135): Accessor<Array<TResult>> {
136 const client = createMemo(() => useQueryClient(queryClient?.()))
137 return createCacheAggregate<Array<TResult>>(
138 (onEvent) => client().getMutationCache().subscribe(onEvent),
139 // Structural sharing against the previous committed value keeps
140 // unchanged mutation states referentially stable across syncs.
141 (prev) =>
142 replaceEqualDeep(prev, getResult(client().getMutationCache(), options())),
143 [],
144 )
145}