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

injectMutationState.md

88 lines2.5 KB

1---
2id: injectMutationState
3title: injectMutationState
4---
5​
6```ts
7function injectMutationState<TResult>(injectMutationStateFn: () => MutationStateOptions<TResult>, options?: InjectMutationStateOptions): Signal<TResult[]>;
8```
9​
10Defined in: [packages/angular-query-experimental/src/inject-mutation-state.ts:106](https://github.com/TanStack/query/blob/main/packages/angular-query-experimental/src/inject-mutation-state.ts#L106)
11​
12Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`
13([MutationFilters](../interfaces/MutationFilters.md)) to narrow down your mutations, and `select` to transform the mutation state.
14​
15## Type Parameters
16​
17### TResult
18​
19`TResult` = [`MutationState`](../interfaces/MutationState.md)\<`unknown`, `Error`, `unknown`, `unknown`\>
20​
21## Parameters
22​
23### injectMutationStateFn
24​
25() => `MutationStateOptions`\<`TResult`\>
26​
27A function returning the `filters` to narrow down matched mutations, and an
28optional `select` to transform the mutation state. Similar to `computed` from Angular, this function runs
29in the reactive context, so signals read inside it re-narrow the matched mutations.
30​
31### options?
32​
33[`InjectMutationStateOptions`](../interfaces/InjectMutationStateOptions.md)
34​
35Additional configuration
36​
37## Returns
38​
39`Signal`\<`TResult`[]\>
40​
41A `Signal` with an Array of whatever `select` returns for each matching mutation.
42​
43## Examples
44​
45Get all variables of all running mutations:
46```angular-ts
47@Component({
48 selector: 'pending-posts',
49 template: `{{ pendingVariables().length }} posts saving...`,
50})
51export class PendingPosts {
52 readonly pendingVariables = injectMutationState(() => ({
53 filters: { status: 'pending' },
54 select: (mutation) => mutation.state.variables,
55 }))
57```
58​
59Get all data for specific mutations via the `mutationKey`:
60```angular-ts
61const mutationKey = ['posts']
62​
63@Component({
64 selector: 'posts',
65 template: `
66 <button (click)="createPost()">
67 Create post ({{ savedPosts().length }} saved so far)
68 </button>
69 `,
70})
71export class Posts {
72 // Some mutation that we want to get the state for
73 readonly createPostMutation = injectMutation(() => ({
74 mutationKey,
75 mutationFn: createPosts,
76 }))
77​
78 readonly savedPosts = injectMutationState(() => ({
79 // this mutation key needs to match the mutation key of the given mutation (see above)
80 filters: { mutationKey, status: 'success' },
81 select: (mutation) => mutation.state.data,
82 }))
83​
84 createPost() {
85 this.createPostMutation.mutate(['New Post'])
86 }
88```