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

useMutationState.ts

158 lines5.0 KB

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