Open History to see the last commit
1import { assertInInjectionContext, inject } from '@angular/core'
2import { QueryClient } from '@tanstack/query-core'
3import { injectExternalStore } from './utils/inject-external-store'
4import type { Signal } from '@angular/core'
5import type {
6 Mutation,
7 MutationCache,
8 MutationFilters,
9 MutationState,
10} from '@tanstack/query-core'
11β
12type MutationTypeFromResult<TResult> = [TResult] extends [
13 MutationState<
14 infer TData,
15 infer TError,
16 infer TVariables,
17 infer TOnMutateResult
18 >,
19]
20 ? Mutation<TData, TError, TVariables, TOnMutateResult>
21 : Mutation
22β
23/**
24 * Filters and optional projection for observing entries in the mutation cache.
25 */
26export type MutationStateOptions<
27 TResult = MutationState,
28 TMutation extends Mutation<any, any, any, any> =
29 MutationTypeFromResult<TResult>,
30> = {
31 /**
32 * Restricts the mutation cache entries included in the result.
33 */
34 filters?: MutationFilters
35 /**
36 * Maps each matching mutation to the value exposed in the result signal.
37 */
38 select?: (mutation: TMutation) => TResult
39}
40β
41/**
42 * Reads and projects the matching entries in a mutation cache.
43 * @param mutationCache - The cache to inspect.
44 * @param options - Filters and an optional projection for each entry.
45 * @returns The selected values, or each matching mutation state.
46 */
47function getResult<
48 TResult = MutationState,
49 TMutation extends Mutation<any, any, any, any> =
50 MutationTypeFromResult<TResult>,
51>(
52 mutationCache: MutationCache,
53 options: MutationStateOptions<TResult, TMutation>,
54): Array<TResult> {
55 return mutationCache
56 .findAll(options.filters)
57 .map(
58 (mutation): TResult =>
59 (options.select
60 ? options.select(mutation as TMutation)
61 : mutation.state) as TResult,
62 )
63}
64β
65/**
66 * Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`
67 * ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation state.
68 * @param options - A function returning the `filters` to narrow down matched mutations, and an optional
69 * `select` to transform the mutation state. Similar to `computed` from Angular, this function runs in the
70 * reactive context, so signals read inside it re-narrow the matched mutations.
71 * @returns A `Signal` with an Array of whatever `select` returns for each matching mutation.
72 * @example
73 * Get all variables of all running mutations:
74 * ```angular-ts
75 * @Component({
76 * selector: 'pending-posts',
77 * template: `{{ pendingVariables().length }} posts saving...`,
78 * })
79 * export class PendingPosts {
80 * readonly pendingVariables = injectMutationState(() => ({
81 * filters: { status: 'pending' },
82 * select: (mutation) => mutation.state.variables,
83 * }))
84 * }
85 * ```
86 * @example
87 * Get all data for specific mutations via the `mutationKey`:
88 * ```angular-ts
89 * const mutationKey = ['posts']
90 *
91 * @Component({
92 * selector: 'posts',
93 * template: `
94 * <button (click)="createPost()">
95 * Create post ({{ savedPosts().length }} saved so far)
96 * </button>
97 * `,
98 * })
99 * export class Posts {
100 * // Some mutation that we want to get the state for
101 * readonly createPostMutation = injectMutation(() => ({
102 * mutationKey,
103 * mutationFn: createPosts,
104 * }))
105 *
106 * readonly savedPosts = injectMutationState(() => ({
107 * // this mutation key needs to match the mutation key of the given mutation (see above)
108 * filters: { mutationKey, status: 'success' },
109 * select: (mutation) => mutation.state.data,
110 * }))
111 *
112 * createPost() {
113 * this.createPostMutation.mutate(['New Post'])
114 * }
115 * }
116 * ```
117 */
118export function injectMutationState<
119 TResult = MutationState,
120 TMutation extends Mutation<any, any, any, any> =
121 MutationTypeFromResult<TResult>,
122>(
123 options: () => MutationStateOptions<TResult, TMutation> = () => ({}),
124): Signal<Array<TResult>> {
125 if (typeof ngDevMode === 'undefined' || ngDevMode) {
126 assertInInjectionContext(injectMutationState)
127 }
128 const queryClient = inject(QueryClient)
129 const mutationCache = queryClient.getMutationCache()
130β
131 return injectExternalStore(
132 () => ({
133 getSnapshot: () => getResult(mutationCache, options()),
134 subscribe: (onStoreChange) => mutationCache.subscribe(onStoreChange),
135 }),
136 {
137 equal: (previous, next) =>
138 previous.length === next.length &&
139 previous.every((value, index) => Object.is(value, next[index])),
140 },
141 )
142}