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

useMutationState.ts

165 lines5.1 KB

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