@tanstack/angular-query 5.0.0 → 5.108.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,9 +12,57 @@ function getResult(mutationCache, options) {
12
12
  return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
13
13
  }
14
14
  /**
15
- * Injects a signal that tracks the state of all mutations.
16
- * @param options - A function that returns mutation state options.
17
- * @returns The signal that tracks the state of all mutations.
15
+ * Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`
16
+ * ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation state.
17
+ * @param options - A function returning the `filters` to narrow down matched mutations, and an optional
18
+ * `select` to transform the mutation state. Similar to `computed` from Angular, this function runs in the
19
+ * reactive context, so signals read inside it re-narrow the matched mutations.
20
+ * @returns A `Signal` with an Array of whatever `select` returns for each matching mutation.
21
+ * @example
22
+ * Get all variables of all running mutations:
23
+ * ```angular-ts
24
+ * @Component({
25
+ * selector: 'pending-posts',
26
+ * template: `{{ pendingVariables().length }} posts saving...`,
27
+ * })
28
+ * export class PendingPosts {
29
+ * readonly pendingVariables = injectMutationState(() => ({
30
+ * filters: { status: 'pending' },
31
+ * select: (mutation) => mutation.state.variables,
32
+ * }))
33
+ * }
34
+ * ```
35
+ * @example
36
+ * Get all data for specific mutations via the `mutationKey`:
37
+ * ```angular-ts
38
+ * const mutationKey = ['posts']
39
+ *
40
+ * @Component({
41
+ * selector: 'posts',
42
+ * template: `
43
+ * <button (click)="createPost()">
44
+ * Create post ({{ savedPosts().length }} saved so far)
45
+ * </button>
46
+ * `,
47
+ * })
48
+ * export class Posts {
49
+ * // Some mutation that we want to get the state for
50
+ * readonly createPostMutation = injectMutation(() => ({
51
+ * mutationKey,
52
+ * mutationFn: createPosts,
53
+ * }))
54
+ *
55
+ * readonly savedPosts = injectMutationState(() => ({
56
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
57
+ * filters: { mutationKey, status: 'success' },
58
+ * select: (mutation) => mutation.state.data,
59
+ * }))
60
+ *
61
+ * createPost() {
62
+ * this.createPostMutation.mutate(['New Post'])
63
+ * }
64
+ * }
65
+ * ```
18
66
  */
19
67
  function injectMutationState(options = () => ({})) {
20
68
  if (typeof ngDevMode === "undefined" || ngDevMode) assertInInjectionContext(injectMutationState);
@@ -1 +1 @@
1
- {"version":3,"file":"inject-mutation-state.mjs","names":[],"sources":["../src/inject-mutation-state.ts"],"sourcesContent":["import { assertInInjectionContext, inject } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport type { Signal } from '@angular/core'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n} from '@tanstack/query-core'\n\ntype MutationTypeFromResult<TResult> = [TResult] extends [\n MutationState<\n infer TData,\n infer TError,\n infer TVariables,\n infer TOnMutateResult\n >,\n]\n ? Mutation<TData, TError, TVariables, TOnMutateResult>\n : Mutation\n\n/**\n * Filters and optional projection for observing entries in the mutation cache.\n */\nexport type MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n /**\n * Restricts the mutation cache entries included in the result.\n */\n filters?: MutationFilters\n /**\n * Maps each matching mutation to the value exposed in the result signal.\n */\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Reads and projects the matching entries in a mutation cache.\n * @param mutationCache - The cache to inspect.\n * @param options - Filters and an optional projection for each entry.\n * @returns The selected values, or each matching mutation state.\n */\nfunction getResult<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n): Array<TResult> {\n return mutationCache\n .findAll(options.filters)\n .map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n )\n}\n\n/**\n * Injects a signal that tracks the state of all mutations.\n * @param options - A function that returns mutation state options.\n * @returns The signal that tracks the state of all mutations.\n */\nexport function injectMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: () => MutationStateOptions<TResult, TMutation> = () => ({}),\n): Signal<Array<TResult>> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectMutationState)\n }\n const queryClient = inject(QueryClient)\n const mutationCache = queryClient.getMutationCache()\n\n return injectExternalStore(\n () => ({\n getSnapshot: () => getResult(mutationCache, options()),\n subscribe: (onStoreChange) => mutationCache.subscribe(onStoreChange),\n }),\n {\n equal: (previous, next) =>\n previous.length === next.length &&\n previous.every((value, index) => Object.is(value, next[index])),\n },\n )\n}\n"],"mappings":";;;;;;;;;;AA8CA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;;;;;;AAOA,SAAgB,oBAKd,iBAAiE,CAAC,IAC1C;CACxB,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,mBAAmB;CAG9C,MAAM,gBADc,OAAO,WACL,CAAA,CAAY,iBAAiB;CAEnD,OAAO,2BACE;EACL,mBAAmB,UAAU,eAAe,QAAQ,CAAC;EACrD,YAAY,kBAAkB,cAAc,UAAU,aAAa;CACrE,IACA,EACE,QAAQ,UAAU,SAChB,SAAS,WAAW,KAAK,UACzB,SAAS,OAAO,OAAO,UAAU,OAAO,GAAG,OAAO,KAAK,MAAM,CAAC,EAClE,CACF;AACF"}
1
+ {"version":3,"file":"inject-mutation-state.mjs","names":[],"sources":["../src/inject-mutation-state.ts"],"sourcesContent":["import { assertInInjectionContext, inject } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport type { Signal } from '@angular/core'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n} from '@tanstack/query-core'\n\ntype MutationTypeFromResult<TResult> = [TResult] extends [\n MutationState<\n infer TData,\n infer TError,\n infer TVariables,\n infer TOnMutateResult\n >,\n]\n ? Mutation<TData, TError, TVariables, TOnMutateResult>\n : Mutation\n\n/**\n * Filters and optional projection for observing entries in the mutation cache.\n */\nexport type MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n /**\n * Restricts the mutation cache entries included in the result.\n */\n filters?: MutationFilters\n /**\n * Maps each matching mutation to the value exposed in the result signal.\n */\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Reads and projects the matching entries in a mutation cache.\n * @param mutationCache - The cache to inspect.\n * @param options - Filters and an optional projection for each entry.\n * @returns The selected values, or each matching mutation state.\n */\nfunction getResult<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n): Array<TResult> {\n return mutationCache\n .findAll(options.filters)\n .map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n )\n}\n\n/**\n * Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`\n * ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation state.\n * @param options - A function returning the `filters` to narrow down matched mutations, and an optional\n * `select` to transform the mutation state. Similar to `computed` from Angular, this function runs in the\n * reactive context, so signals read inside it re-narrow the matched mutations.\n * @returns A `Signal` with an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```angular-ts\n * @Component({\n * selector: 'pending-posts',\n * template: `{{ pendingVariables().length }} posts saving...`,\n * })\n * export class PendingPosts {\n * readonly pendingVariables = injectMutationState(() => ({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * }))\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```angular-ts\n * const mutationKey = ['posts']\n *\n * @Component({\n * selector: 'posts',\n * template: `\n * <button (click)=\"createPost()\">\n * Create post ({{ savedPosts().length }} saved so far)\n * </button>\n * `,\n * })\n * export class Posts {\n * // Some mutation that we want to get the state for\n * readonly createPostMutation = injectMutation(() => ({\n * mutationKey,\n * mutationFn: createPosts,\n * }))\n *\n * readonly savedPosts = injectMutationState(() => ({\n * // this mutation key needs to match the mutation key of the given mutation (see above)\n * filters: { mutationKey, status: 'success' },\n * select: (mutation) => mutation.state.data,\n * }))\n *\n * createPost() {\n * this.createPostMutation.mutate(['New Post'])\n * }\n * }\n * ```\n */\nexport function injectMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: () => MutationStateOptions<TResult, TMutation> = () => ({}),\n): Signal<Array<TResult>> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectMutationState)\n }\n const queryClient = inject(QueryClient)\n const mutationCache = queryClient.getMutationCache()\n\n return injectExternalStore(\n () => ({\n getSnapshot: () => getResult(mutationCache, options()),\n subscribe: (onStoreChange) => mutationCache.subscribe(onStoreChange),\n }),\n {\n equal: (previous, next) =>\n previous.length === next.length &&\n previous.every((value, index) => Object.is(value, next[index])),\n },\n )\n}\n"],"mappings":";;;;;;;;;;AA8CA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,SAAgB,oBAKd,iBAAiE,CAAC,IAC1C;CACxB,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,mBAAmB;CAG9C,MAAM,gBADc,OAAO,WACL,CAAA,CAAY,iBAAiB;CAEnD,OAAO,2BACE;EACL,mBAAmB,UAAU,eAAe,QAAQ,CAAC;EACrD,YAAY,kBAAkB,cAAc,UAAU,aAAa;CACrE,IACA,EACE,QAAQ,UAAU,SAChB,SAAS,WAAW,KAAK,UACzB,SAAS,OAAO,OAAO,UAAU,OAAO,GAAG,OAAO,KAAK,MAAM,CAAC,EAClE,CACF;AACF"}
@@ -1,30 +1,135 @@
1
1
  import { DefaultError } from '@tanstack/query-core';
2
2
  import { CreateMutationOptions, CreateMutationResult } from './types.js';
3
3
  /**
4
- * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
5
- * Unlike queries, mutations are not run automatically.
4
+ * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
5
+ * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
6
6
  * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this
7
- * function runs in the reactive context, so signals read inside it drive the mutation.
8
- * @returns The mutation result, including `mutate` and `mutateAsync`.
7
+ * function runs in the reactive context, so signals read inside it drive the mutation's options.
8
+ * @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them
9
+ * (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
10
+ * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
11
+ * `data` is defined.
12
+ * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
13
+ * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
14
+ * the shared mutation definition. Callbacks defined in `optionsFn` fire for every mutation; per-call
15
+ * callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,
16
+ * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
9
17
  * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations
10
- * @see {@link mutationOptions} to share these options between `injectMutation` and `injectMutationState`.
18
+ * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
19
+ * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
11
20
  * @example
12
21
  * ```angular-ts
13
22
  * @Component({
23
+ * selector: 'todos',
14
24
  * template: `
15
- * @if (mutation.isPending()) {
16
- * Saving...
17
- * } @else if (mutation.isError()) {
18
- * <span>Error: {{ mutation.error()?.message }}</span>
25
+ * @if (addMutation.isPending()) {
26
+ * <span>Adding todo...</span>
27
+ * } @else if (addMutation.isError()) {
28
+ * <div>An error occurred: {{ addMutation.error()?.message }}</div>
19
29
  * }
20
- * <button (click)="mutation.mutate({ title: 'New post' })">Create</button>
30
+ * <button (click)="addMutation.mutate('Item')">Add</button>
21
31
  * `,
22
32
  * })
23
- * export class CreatePost {
24
- * readonly mutation = injectMutation(() => ({
25
- * mutationFn: createPost,
33
+ * export class Todos {
34
+ * readonly #queryClient = inject(QueryClient)
35
+ *
36
+ * readonly addMutation = injectMutation(() => ({
37
+ * mutationFn: addTodo,
38
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
26
39
  * }))
27
40
  * }
28
41
  * ```
42
+ * @example
43
+ * Optimistic update via `onMutate`, rolling back on `onError`:
44
+ * ```angular-ts
45
+ * @Component({
46
+ * selector: 'todos',
47
+ * template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
48
+ * })
49
+ * export class Todos {
50
+ * readonly #queryClient = inject(QueryClient)
51
+ *
52
+ * readonly addMutation = injectMutation(() => ({
53
+ * mutationFn: addTodo,
54
+ * onMutate: async (newTodo) => {
55
+ * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
56
+ * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
57
+ *
58
+ * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
59
+ * ...(old ?? []),
60
+ * newTodo,
61
+ * ])
62
+ *
63
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
64
+ * return { previousTodos }
65
+ * },
66
+ * onError: (_err, _newTodo, onMutateResult) => {
67
+ * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
68
+ * },
69
+ * onSettled: () => {
70
+ * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
71
+ * },
72
+ * }))
73
+ * }
74
+ * ```
75
+ * @example
76
+ * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per
77
+ * call instead, so you can wait for all of them when they succeed:
78
+ * ```angular-ts
79
+ * @Component({
80
+ * selector: 'todos',
81
+ * template: `
82
+ * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
83
+ * `,
84
+ * })
85
+ * export class Todos {
86
+ * readonly #queryClient = inject(QueryClient)
87
+ *
88
+ * readonly addMutation = injectMutation(() => ({
89
+ * mutationFn: addTodo,
90
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
91
+ * }))
92
+ *
93
+ * async handleAddAll(todos: Array<string>) {
94
+ * try {
95
+ * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
96
+ * } catch (error) {
97
+ * console.error('Failed to add todos:', error)
98
+ * }
99
+ * }
100
+ * }
101
+ * ```
102
+ * @example
103
+ * If some of the mutations above can fail independently of the others, and you want to know which ones did —
104
+ * rather than losing that information the moment the first one rejects — swap `Promise.all` for
105
+ * `Promise.allSettled`:
106
+ * ```angular-ts
107
+ * @Component({
108
+ * selector: 'todos',
109
+ * template: `
110
+ * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
111
+ * `,
112
+ * })
113
+ * export class Todos {
114
+ * readonly #queryClient = inject(QueryClient)
115
+ *
116
+ * readonly addMutation = injectMutation(() => ({
117
+ * mutationFn: addTodo,
118
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
119
+ * }))
120
+ *
121
+ * async handleAddAll(todos: Array<string>) {
122
+ * const addResults = await Promise.allSettled(
123
+ * todos.map((todo) => this.addMutation.mutateAsync(todo)),
124
+ * )
125
+ *
126
+ * addResults.forEach((addResult, index) => {
127
+ * if (addResult.status === 'rejected') {
128
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
129
+ * }
130
+ * })
131
+ * }
132
+ * }
133
+ * ```
29
134
  */
30
135
  export declare function injectMutation<TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown>(optionsFn: () => CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>): CreateMutationResult<TData, TError, TVariables, TOnMutateResult>;
@@ -1,35 +1,140 @@
1
- import { injectQueryZone } from "./utils/inject-query-zone.mjs";
2
1
  import { injectExternalStore } from "./utils/inject-external-store.mjs";
3
2
  import { injectPendingTasksLifecycle } from "./utils/inject-pending-tasks-lifecycle.mjs";
3
+ import { injectQueryZone } from "./utils/inject-query-zone.mjs";
4
4
  import { mutationResultFields } from "./utils/result-fields.mjs";
5
5
  import { signalProxy } from "./utils/signal-proxy.mjs";
6
6
  import { MutationObserver, QueryClient, noop } from "@tanstack/query-core";
7
7
  import { assertInInjectionContext, computed, effect, inject, untracked } from "@angular/core";
8
8
  // src/inject-mutation.ts
9
9
  /**
10
- * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
11
- * Unlike queries, mutations are not run automatically.
10
+ * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.
11
+ * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.
12
12
  * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this
13
- * function runs in the reactive context, so signals read inside it drive the mutation.
14
- * @returns The mutation result, including `mutate` and `mutateAsync`.
13
+ * function runs in the reactive context, so signals read inside it drive the mutation's options.
14
+ * @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them
15
+ * (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,
16
+ * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether
17
+ * `data` is defined.
18
+ * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a
19
+ * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to
20
+ * the shared mutation definition. Callbacks defined in `optionsFn` fire for every mutation; per-call
21
+ * callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,
22
+ * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.
15
23
  * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations
16
- * @see {@link mutationOptions} to share these options between `injectMutation` and `injectMutationState`.
24
+ * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look
25
+ * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).
26
+ * @example
27
+ * ```angular-ts
28
+ * @Component({
29
+ * selector: 'todos',
30
+ * template: `
31
+ * @if (addMutation.isPending()) {
32
+ * <span>Adding todo...</span>
33
+ * } @else if (addMutation.isError()) {
34
+ * <div>An error occurred: {{ addMutation.error()?.message }}</div>
35
+ * }
36
+ * <button (click)="addMutation.mutate('Item')">Add</button>
37
+ * `,
38
+ * })
39
+ * export class Todos {
40
+ * readonly #queryClient = inject(QueryClient)
41
+ *
42
+ * readonly addMutation = injectMutation(() => ({
43
+ * mutationFn: addTodo,
44
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
45
+ * }))
46
+ * }
47
+ * ```
48
+ * @example
49
+ * Optimistic update via `onMutate`, rolling back on `onError`:
50
+ * ```angular-ts
51
+ * @Component({
52
+ * selector: 'todos',
53
+ * template: `<button (click)="addMutation.mutate('Item')">Add</button>`,
54
+ * })
55
+ * export class Todos {
56
+ * readonly #queryClient = inject(QueryClient)
57
+ *
58
+ * readonly addMutation = injectMutation(() => ({
59
+ * mutationFn: addTodo,
60
+ * onMutate: async (newTodo) => {
61
+ * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })
62
+ * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])
63
+ *
64
+ * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [
65
+ * ...(old ?? []),
66
+ * newTodo,
67
+ * ])
68
+ *
69
+ * // Passed to `onError` as `onMutateResult` if the mutation fails.
70
+ * return { previousTodos }
71
+ * },
72
+ * onError: (_err, _newTodo, onMutateResult) => {
73
+ * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
74
+ * },
75
+ * onSettled: () => {
76
+ * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })
77
+ * },
78
+ * }))
79
+ * }
80
+ * ```
17
81
  * @example
82
+ * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per
83
+ * call instead, so you can wait for all of them when they succeed:
18
84
  * ```angular-ts
19
85
  * @Component({
86
+ * selector: 'todos',
20
87
  * template: `
21
- * @if (mutation.isPending()) {
22
- * Saving...
23
- * } @else if (mutation.isError()) {
24
- * <span>Error: {{ mutation.error()?.message }}</span>
88
+ * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
89
+ * `,
90
+ * })
91
+ * export class Todos {
92
+ * readonly #queryClient = inject(QueryClient)
93
+ *
94
+ * readonly addMutation = injectMutation(() => ({
95
+ * mutationFn: addTodo,
96
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
97
+ * }))
98
+ *
99
+ * async handleAddAll(todos: Array<string>) {
100
+ * try {
101
+ * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))
102
+ * } catch (error) {
103
+ * console.error('Failed to add todos:', error)
25
104
  * }
26
- * <button (click)="mutation.mutate({ title: 'New post' })">Create</button>
105
+ * }
106
+ * }
107
+ * ```
108
+ * @example
109
+ * If some of the mutations above can fail independently of the others, and you want to know which ones did —
110
+ * rather than losing that information the moment the first one rejects — swap `Promise.all` for
111
+ * `Promise.allSettled`:
112
+ * ```angular-ts
113
+ * @Component({
114
+ * selector: 'todos',
115
+ * template: `
116
+ * <button (click)="handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])">Add all</button>
27
117
  * `,
28
118
  * })
29
- * export class CreatePost {
30
- * readonly mutation = injectMutation(() => ({
31
- * mutationFn: createPost,
119
+ * export class Todos {
120
+ * readonly #queryClient = inject(QueryClient)
121
+ *
122
+ * readonly addMutation = injectMutation(() => ({
123
+ * mutationFn: addTodo,
124
+ * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
32
125
  * }))
126
+ *
127
+ * async handleAddAll(todos: Array<string>) {
128
+ * const addResults = await Promise.allSettled(
129
+ * todos.map((todo) => this.addMutation.mutateAsync(todo)),
130
+ * )
131
+ *
132
+ * addResults.forEach((addResult, index) => {
133
+ * if (addResult.status === 'rejected') {
134
+ * console.error(`Failed to add "${todos[index]}":`, addResult.reason)
135
+ * }
136
+ * })
137
+ * }
33
138
  * }
34
139
  * ```
35
140
  */
@@ -1 +1 @@
1
- {"version":3,"file":"inject-mutation.mjs","names":[],"sources":["../src/inject-mutation.ts"],"sourcesContent":["import {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { MutationObserver, QueryClient, noop } from '@tanstack/query-core'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { mutationResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type { DefaultError } from '@tanstack/query-core'\nimport type {\n CreateMutateAsyncFunction,\n CreateMutateFunction,\n CreateMutationOptions,\n CreateMutationResult,\n} from './types'\n\n/**\n * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.\n * Unlike queries, mutations are not run automatically.\n * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it drive the mutation.\n * @returns The mutation result, including `mutate` and `mutateAsync`.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations\n * @see {@link mutationOptions} to share these options between `injectMutation` and `injectMutationState`.\n * @example\n * ```angular-ts\n * @Component({\n * template: `\n * @if (mutation.isPending()) {\n * Saving...\n * } @else if (mutation.isError()) {\n * <span>Error: {{ mutation.error()?.message }}</span>\n * }\n * <button (click)=\"mutation.mutate({ title: 'New post' })\">Create</button>\n * `,\n * })\n * export class CreatePost {\n * readonly mutation = injectMutation(() => ({\n * mutationFn: createPost,\n * }))\n * }\n * ```\n */\nexport function injectMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n optionsFn: () => CreateMutationOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectMutation)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const observerSignal = computed(\n () => new MutationObserver(queryClient, untracked(optionsSignal)),\n )\n\n // Configure the observer outside the result computation. Mutation-cache\n // listeners can synchronously read the public result while setOptions emits.\n effect(() => {\n const options = optionsSignal()\n outsideZone(() => untracked(() => observerSignal().setOptions(options)))\n })\n\n const mutationStateSignal = injectExternalStore(() => {\n const observer = observerSignal()\n return {\n getSnapshot: () => observer.getCurrentResult(),\n subscribe: (onStoreChange) => observer.subscribe(onStoreChange),\n }\n })\n\n const mutate: CreateMutateFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n mutateAsync(...args).catch(noop)\n }\n\n let pendingInvocations = 0\n\n const mutateAsync: CreateMutateAsyncFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n return outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n pendingInvocations++\n lifecycle.setPending(true)\n // Track invocations, not the observer's latest result: reset or a later\n // mutation completing must not release work which is still running.\n const settled = () => {\n pendingInvocations--\n lifecycle.setPending(pendingInvocations > 0)\n }\n try {\n return observer\n .mutate(args[0] as TVariables, args[1])\n .finally(settled)\n } catch (error) {\n settled()\n throw error\n }\n }),\n )\n }\n\n const reset = () => {\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n observer.reset()\n }),\n )\n }\n\n return Object.assign(signalProxy(mutationStateSignal, mutationResultFields), {\n mutate,\n mutateAsync,\n reset,\n }) as unknown as CreateMutationResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,SAAgB,eAMd,WAMkE;CAClE,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,cAAc;CAEzC,MAAM,cAAc,gBAAgB;CACpC,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,YAAY,4BAA4B;CAE9C,MAAM,gBAAgB,SAAS,SAAS;CAExC,MAAM,iBAAiB,eACf,IAAI,iBAAiB,aAAa,UAAU,aAAa,CAAC,CAClE;CAIA,aAAa;EACX,MAAM,UAAU,cAAc;EAC9B,kBAAkB,gBAAgB,eAAe,CAAC,CAAC,WAAW,OAAO,CAAC,CAAC;CACzE,CAAC;CAED,MAAM,sBAAsB,0BAA0B;EACpD,MAAM,WAAW,eAAe;EAChC,OAAO;GACL,mBAAmB,SAAS,iBAAiB;GAC7C,YAAY,kBAAkB,SAAS,UAAU,aAAa;EAChE;CACF,CAAC;CAED,MAAM,UAKD,GAAG,SAAS;EACf,YAAY,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI;CACjC;CAEA,IAAI,qBAAqB;CAEzB,MAAM,eAKD,GAAG,SAAS;EACf,OAAO,kBACL,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC;GACA,UAAU,WAAW,IAAI;GAGzB,MAAM,gBAAgB;IACpB;IACA,UAAU,WAAW,qBAAqB,CAAC;GAC7C;GACA,IAAI;IACF,OAAO,SACJ,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CACtC,QAAQ,OAAO;GACpB,SAAS,OAAO;IACd,QAAQ;IACR,MAAM;GACR;EACF,CAAC,CACH;CACF;CAEA,MAAM,cAAc;EAClB,kBACE,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC,SAAS,MAAM;EACjB,CAAC,CACH;CACF;CAEA,OAAO,OAAO,OAAO,YAAY,qBAAqB,oBAAoB,GAAG;EAC3E;EACA;EACA;CACF,CAAC;AAMH"}
1
+ {"version":3,"file":"inject-mutation.mjs","names":[],"sources":["../src/inject-mutation.ts"],"sourcesContent":["import {\n assertInInjectionContext,\n computed,\n effect,\n inject,\n untracked,\n} from '@angular/core'\nimport { MutationObserver, QueryClient, noop } from '@tanstack/query-core'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport { injectPendingTasksLifecycle } from './utils/inject-pending-tasks-lifecycle'\nimport { injectQueryZone } from './utils/inject-query-zone'\nimport { mutationResultFields } from './utils/result-fields'\nimport { signalProxy } from './utils/signal-proxy'\nimport type { DefaultError } from '@tanstack/query-core'\nimport type {\n CreateMutateAsyncFunction,\n CreateMutateFunction,\n CreateMutationOptions,\n CreateMutationResult,\n} from './types'\n\n/**\n * Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects.\n * `injectMutation` is the function for that. Unlike queries, mutations are not run automatically.\n * @param optionsFn - A function that returns mutation options. Similar to `computed` from Angular, this\n * function runs in the reactive context, so signals read inside it drive the mutation's options.\n * @returns The mutation result. Value fields are exposed as a `Signal` — read `data`/`error` by calling them\n * (e.g. `mutation.data()`) — while function fields (`mutate`, `mutateAsync`, `reset`) are called directly,\n * unchanged. `isSuccess`/`isError`/`isPending`/`isIdle` are type-guard methods you can call to narrow whether\n * `data` is defined.\n * @remarks `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a\n * second argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to\n * the shared mutation definition. Callbacks defined in `optionsFn` fire for every mutation; per-call\n * callbacks fire only for the latest call you've made — `mutateAsync` gives you a promise per call instead,\n * so you can await `Promise.all`/`Promise.allSettled` over several calls and see each one's outcome.\n * @see https://tanstack.com/query/latest/docs/framework/angular/guides/mutations\n * @see {@link mutationOptions} to share these options across multiple `injectMutation` call sites, or to look\n * the mutation up elsewhere via its `mutationKey` (e.g. with `injectMutationState`).\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * @if (addMutation.isPending()) {\n * <span>Adding todo...</span>\n * } @else if (addMutation.isError()) {\n * <div>An error occurred: {{ addMutation.error()?.message }}</div>\n * }\n * <button (click)=\"addMutation.mutate('Item')\">Add</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n * }\n * ```\n * @example\n * Optimistic update via `onMutate`, rolling back on `onError`:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `<button (click)=\"addMutation.mutate('Item')\">Add</button>`,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onMutate: async (newTodo) => {\n * await this.#queryClient.cancelQueries({ queryKey: ['todos'] })\n * const previousTodos = this.#queryClient.getQueryData<Array<string>>(['todos'])\n *\n * this.#queryClient.setQueryData<Array<string>>(['todos'], (old) => [\n * ...(old ?? []),\n * newTodo,\n * ])\n *\n * // Passed to `onError` as `onMutateResult` if the mutation fails.\n * return { previousTodos }\n * },\n * onError: (_err, _newTodo, onMutateResult) => {\n * this.#queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)\n * },\n * onSettled: () => {\n * this.#queryClient.invalidateQueries({ queryKey: ['todos'] })\n * },\n * }))\n * }\n * ```\n * @example\n * Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a promise per\n * call instead, so you can wait for all of them when they succeed:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * <button (click)=\"handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])\">Add all</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n *\n * async handleAddAll(todos: Array<string>) {\n * try {\n * await Promise.all(todos.map((todo) => this.addMutation.mutateAsync(todo)))\n * } catch (error) {\n * console.error('Failed to add todos:', error)\n * }\n * }\n * }\n * ```\n * @example\n * If some of the mutations above can fail independently of the others, and you want to know which ones did —\n * rather than losing that information the moment the first one rejects — swap `Promise.all` for\n * `Promise.allSettled`:\n * ```angular-ts\n * @Component({\n * selector: 'todos',\n * template: `\n * <button (click)=\"handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])\">Add all</button>\n * `,\n * })\n * export class Todos {\n * readonly #queryClient = inject(QueryClient)\n *\n * readonly addMutation = injectMutation(() => ({\n * mutationFn: addTodo,\n * onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),\n * }))\n *\n * async handleAddAll(todos: Array<string>) {\n * const addResults = await Promise.allSettled(\n * todos.map((todo) => this.addMutation.mutateAsync(todo)),\n * )\n *\n * addResults.forEach((addResult, index) => {\n * if (addResult.status === 'rejected') {\n * console.error(`Failed to add \"${todos[index]}\":`, addResult.reason)\n * }\n * })\n * }\n * }\n * ```\n */\nexport function injectMutation<\n TData = unknown,\n TError = DefaultError,\n TVariables = void,\n TOnMutateResult = unknown,\n>(\n optionsFn: () => CreateMutationOptions<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >,\n): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectMutation)\n }\n const outsideZone = injectQueryZone()\n const queryClient = inject(QueryClient)\n const lifecycle = injectPendingTasksLifecycle()\n\n const optionsSignal = computed(optionsFn)\n\n const observerSignal = computed(\n () => new MutationObserver(queryClient, untracked(optionsSignal)),\n )\n\n // Configure the observer outside the result computation. Mutation-cache\n // listeners can synchronously read the public result while setOptions emits.\n effect(() => {\n const options = optionsSignal()\n outsideZone(() => untracked(() => observerSignal().setOptions(options)))\n })\n\n const mutationStateSignal = injectExternalStore(() => {\n const observer = observerSignal()\n return {\n getSnapshot: () => observer.getCurrentResult(),\n subscribe: (onStoreChange) => observer.subscribe(onStoreChange),\n }\n })\n\n const mutate: CreateMutateFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n mutateAsync(...args).catch(noop)\n }\n\n let pendingInvocations = 0\n\n const mutateAsync: CreateMutateAsyncFunction<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n > = (...args) => {\n return outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n pendingInvocations++\n lifecycle.setPending(true)\n // Track invocations, not the observer's latest result: reset or a later\n // mutation completing must not release work which is still running.\n const settled = () => {\n pendingInvocations--\n lifecycle.setPending(pendingInvocations > 0)\n }\n try {\n return observer\n .mutate(args[0] as TVariables, args[1])\n .finally(settled)\n } catch (error) {\n settled()\n throw error\n }\n }),\n )\n }\n\n const reset = () => {\n outsideZone(() =>\n untracked(() => {\n const observer = observerSignal()\n observer.setOptions(optionsSignal())\n observer.reset()\n }),\n )\n }\n\n return Object.assign(signalProxy(mutationStateSignal, mutationResultFields), {\n mutate,\n mutateAsync,\n reset,\n }) as unknown as CreateMutationResult<\n TData,\n TError,\n TVariables,\n TOnMutateResult\n >\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyJA,SAAgB,eAMd,WAMkE;CAClE,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,cAAc;CAEzC,MAAM,cAAc,gBAAgB;CACpC,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,YAAY,4BAA4B;CAE9C,MAAM,gBAAgB,SAAS,SAAS;CAExC,MAAM,iBAAiB,eACf,IAAI,iBAAiB,aAAa,UAAU,aAAa,CAAC,CAClE;CAIA,aAAa;EACX,MAAM,UAAU,cAAc;EAC9B,kBAAkB,gBAAgB,eAAe,CAAC,CAAC,WAAW,OAAO,CAAC,CAAC;CACzE,CAAC;CAED,MAAM,sBAAsB,0BAA0B;EACpD,MAAM,WAAW,eAAe;EAChC,OAAO;GACL,mBAAmB,SAAS,iBAAiB;GAC7C,YAAY,kBAAkB,SAAS,UAAU,aAAa;EAChE;CACF,CAAC;CAED,MAAM,UAKD,GAAG,SAAS;EACf,YAAY,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI;CACjC;CAEA,IAAI,qBAAqB;CAEzB,MAAM,eAKD,GAAG,SAAS;EACf,OAAO,kBACL,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC;GACA,UAAU,WAAW,IAAI;GAGzB,MAAM,gBAAgB;IACpB;IACA,UAAU,WAAW,qBAAqB,CAAC;GAC7C;GACA,IAAI;IACF,OAAO,SACJ,OAAO,KAAK,IAAkB,KAAK,EAAE,CAAC,CACtC,QAAQ,OAAO;GACpB,SAAS,OAAO;IACd,QAAQ;IACR,MAAM;GACR;EACF,CAAC,CACH;CACF;CAEA,MAAM,cAAc;EAClB,kBACE,gBAAgB;GACd,MAAM,WAAW,eAAe;GAChC,SAAS,WAAW,cAAc,CAAC;GACnC,SAAS,MAAM;EACjB,CAAC,CACH;CACF;CAEA,OAAO,OAAO,OAAO,YAAY,qBAAqB,oBAAoB,GAAG;EAC3E;EACA;EACA;CACF,CAAC;AAMH"}
@@ -1,31 +1,129 @@
1
1
  import { Signal } from '@angular/core';
2
2
  import { InjectQueriesOptions, QueriesResults } from './inject-queries.types.js';
3
3
  /**
4
- * Injects multiple queries that run in parallel and react to Angular signals.
5
- * @param optionsFn - A function that returns the queries' options. Similar to `computed` from Angular,
6
- * this function runs in the reactive context, so signals read inside it drive the queries.
7
- * @returns A signal containing the query results in the same order as the input queries.
4
+ * Injects a signal to fetch a variable number of queries.
5
+ *
6
+ * The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
7
+ * the same query key more than once in the array of query objects may cause some data to be shared between
8
+ * queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
9
+ * structure.
10
+ *
11
+ * The `combine` option can be used to combine the results of the queries into a single value.
12
+ * @param optionsFn - A function returning the queries' options — an array of query option objects under
13
+ * `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
14
+ * reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
15
+ * @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
16
+ * results, in the same order as the input. When `combine` is provided, this is the value returned by
17
+ * `combine` instead.
18
+ * @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
19
+ * from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
20
+ * the `select` parameter of a query object written inline cannot be contextually typed from that same
21
+ * object's `queryFn`, so it falls back to `unknown` — a
22
+ * [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
23
+ * parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
24
+ * object _before_ it reaches `injectQueries`, to work around this — see the example below.
8
25
  * @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries
9
26
  * @example
10
27
  * ```angular-ts
11
28
  * @Component({
12
- * selector: 'users',
29
+ * selector: 'posts',
13
30
  * template: `
14
- * @for (query of userQueries(); track $index) {
15
- * @if (query.isSuccess()) {
16
- * <p>{{ query.data().name }}</p>
31
+ * <ul>
32
+ * @for (query of postQueries(); track $index) {
33
+ * @if (query.isPending()) {
34
+ * <li>Loading...</li>
35
+ * } @else if (query.isError()) {
36
+ * <li>Error: {{ query.error()?.message }}</li>
37
+ * } @else {
38
+ * <li>{{ query.data().title }}</li>
39
+ * }
17
40
  * }
41
+ * </ul>
42
+ * `,
43
+ * })
44
+ * export class Posts {
45
+ * readonly ids = signal([1, 2, 3])
46
+ *
47
+ * readonly postQueries = injectQueries(() => ({
48
+ * queries: this.ids().map((id) => ({
49
+ * queryKey: ['post', id],
50
+ * queryFn: () => fetchPost(id),
51
+ * staleTime: Infinity,
52
+ * })),
53
+ * }))
54
+ * }
55
+ * ```
56
+ * @example
57
+ * Combining results into a single value:
58
+ * ```angular-ts
59
+ * @Component({
60
+ * selector: 'posts',
61
+ * template: `
62
+ * @if (combined().isPending) {
63
+ * Loading...
64
+ * } @else if (combined().isError) {
65
+ * Error loading posts
66
+ * } @else {
67
+ * <ul>
68
+ * @for (post of combined().data; track post?.id) {
69
+ * <li>{{ post?.title }}</li>
70
+ * }
71
+ * </ul>
18
72
  * }
19
73
  * `,
20
74
  * })
21
- * export class UsersComponent {
22
- * readonly users = input.required<Array<User>>()
75
+ * export class Posts {
76
+ * readonly ids = signal([1, 2, 3])
23
77
  *
24
- * readonly userQueries = injectQueries(() => ({
25
- * queries: this.users().map((user) => ({
26
- * queryKey: ['user', user.id],
27
- * queryFn: () => fetchUserById(user.id),
78
+ * readonly combined = injectQueries(() => ({
79
+ * queries: this.ids().map((id) => ({
80
+ * queryKey: ['post', id],
81
+ * queryFn: () => fetchPost(id),
28
82
  * })),
83
+ * combine: (postQueries) => ({
84
+ * data: postQueries.map((query) => query.data),
85
+ * isPending: postQueries.some((query) => query.isPending),
86
+ * isError: postQueries.some((query) => query.isError),
87
+ * }),
88
+ * }))
89
+ * }
90
+ * ```
91
+ * @example
92
+ * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
93
+ * `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
94
+ * resolved before it reaches `injectQueries`:
95
+ * ```angular-ts
96
+ * const postOptions = (id: number) =>
97
+ * queryOptions({
98
+ * queryKey: ['post', id],
99
+ * queryFn: () => fetchPost(id),
100
+ * })
101
+ *
102
+ * @Component({
103
+ * selector: 'post-title',
104
+ * template: `<h1>{{ fixed()[0].data() }}</h1>`,
105
+ * })
106
+ * export class PostTitle {
107
+ * readonly id = signal(1)
108
+ *
109
+ * readonly broken = injectQueries(() => ({
110
+ * queries: [
111
+ * {
112
+ * ...postOptions(this.id()),
113
+ * // ❌ `data` is `unknown` here
114
+ * select: (data) => data.title,
115
+ * },
116
+ * ],
117
+ * }))
118
+ *
119
+ * readonly fixed = injectQueries(() => ({
120
+ * queries: [
121
+ * queryOptions({
122
+ * ...postOptions(this.id()),
123
+ * // ✅ `data` is `Post`
124
+ * select: (data) => data.title,
125
+ * }),
126
+ * ],
29
127
  * }))
30
128
  * }
31
129
  * ```