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