@tanstack/angular-query 5.0.0 → 5.108.0
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.
- package/inject-infinite-query.d.ts +169 -32
- package/inject-infinite-query.mjs.map +1 -1
- package/inject-is-fetching.d.ts +35 -4
- package/inject-is-fetching.mjs +35 -4
- package/inject-is-fetching.mjs.map +1 -1
- package/inject-is-mutating.d.ts +19 -4
- package/inject-is-mutating.mjs +19 -4
- package/inject-is-mutating.mjs.map +1 -1
- package/inject-is-restoring.d.ts +5 -3
- package/inject-is-restoring.mjs +5 -3
- package/inject-is-restoring.mjs.map +1 -1
- package/inject-mutation-state.d.ts +51 -3
- package/inject-mutation-state.mjs +51 -3
- package/inject-mutation-state.mjs.map +1 -1
- package/inject-mutation.d.ts +118 -13
- package/inject-mutation.mjs +118 -13
- package/inject-mutation.mjs.map +1 -1
- package/inject-queries.d.ts +112 -14
- package/inject-queries.mjs +112 -14
- package/inject-queries.mjs.map +1 -1
- package/inject-queries.types.d.ts +25 -5
- package/inject-query.d.ts +3 -1
- package/inject-query.mjs.map +1 -1
- package/package.json +2 -2
- package/providers.d.ts +31 -6
- package/providers.mjs +31 -6
- package/providers.mjs.map +1 -1
- package/query-options.d.ts +7 -0
- package/query-options.mjs.map +1 -1
- package/schematics/migrate-from-experimental/index.js +2 -2
- package/schematics/ng-add/index.js +1 -1
- package/types.d.ts +36 -5
|
@@ -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
|
|
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"}
|
package/inject-mutation.d.ts
CHANGED
|
@@ -1,30 +1,135 @@
|
|
|
1
1
|
import { DefaultError } from '@tanstack/query-core';
|
|
2
2
|
import { CreateMutationOptions, CreateMutationResult } from './types.js';
|
|
3
3
|
/**
|
|
4
|
-
*
|
|
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
|
|
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
|
|
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 (
|
|
16
|
-
*
|
|
17
|
-
* } @else if (
|
|
18
|
-
* <
|
|
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)="
|
|
30
|
+
* <button (click)="addMutation.mutate('Item')">Add</button>
|
|
21
31
|
* `,
|
|
22
32
|
* })
|
|
23
|
-
* export class
|
|
24
|
-
* readonly
|
|
25
|
-
*
|
|
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>;
|
package/inject-mutation.mjs
CHANGED
|
@@ -7,31 +7,136 @@ 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
|
-
*
|
|
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
|
|
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
|
|
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`).
|
|
17
26
|
* @example
|
|
18
27
|
* ```angular-ts
|
|
19
28
|
* @Component({
|
|
29
|
+
* selector: 'todos',
|
|
20
30
|
* template: `
|
|
21
|
-
* @if (
|
|
22
|
-
*
|
|
23
|
-
* } @else if (
|
|
24
|
-
* <
|
|
31
|
+
* @if (addMutation.isPending()) {
|
|
32
|
+
* <span>Adding todo...</span>
|
|
33
|
+
* } @else if (addMutation.isError()) {
|
|
34
|
+
* <div>An error occurred: {{ addMutation.error()?.message }}</div>
|
|
25
35
|
* }
|
|
26
|
-
* <button (click)="
|
|
36
|
+
* <button (click)="addMutation.mutate('Item')">Add</button>
|
|
27
37
|
* `,
|
|
28
38
|
* })
|
|
29
|
-
* export class
|
|
30
|
-
* readonly
|
|
31
|
-
*
|
|
39
|
+
* export class Todos {
|
|
40
|
+
* readonly #queryClient = inject(QueryClient)
|
|
41
|
+
*
|
|
42
|
+
* readonly addMutation = injectMutation(() => ({
|
|
43
|
+
* mutationFn: addTodo,
|
|
44
|
+
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
32
45
|
* }))
|
|
33
46
|
* }
|
|
34
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
|
+
* ```
|
|
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:
|
|
84
|
+
* ```angular-ts
|
|
85
|
+
* @Component({
|
|
86
|
+
* selector: 'todos',
|
|
87
|
+
* template: `
|
|
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)
|
|
104
|
+
* }
|
|
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>
|
|
117
|
+
* `,
|
|
118
|
+
* })
|
|
119
|
+
* export class Todos {
|
|
120
|
+
* readonly #queryClient = inject(QueryClient)
|
|
121
|
+
*
|
|
122
|
+
* readonly addMutation = injectMutation(() => ({
|
|
123
|
+
* mutationFn: addTodo,
|
|
124
|
+
* onSuccess: () => this.#queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
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
|
+
* }
|
|
138
|
+
* }
|
|
139
|
+
* ```
|
|
35
140
|
*/
|
|
36
141
|
function injectMutation(optionsFn) {
|
|
37
142
|
if (typeof ngDevMode === "undefined" || ngDevMode) assertInInjectionContext(injectMutation);
|
package/inject-mutation.mjs.map
CHANGED
|
@@ -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"}
|
package/inject-queries.d.ts
CHANGED
|
@@ -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
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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: '
|
|
29
|
+
* selector: 'posts',
|
|
13
30
|
* template: `
|
|
14
|
-
*
|
|
15
|
-
* @
|
|
16
|
-
*
|
|
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
|
|
22
|
-
* readonly
|
|
75
|
+
* export class Posts {
|
|
76
|
+
* readonly ids = signal([1, 2, 3])
|
|
23
77
|
*
|
|
24
|
-
* readonly
|
|
25
|
-
* queries: this.
|
|
26
|
-
* queryKey: ['
|
|
27
|
-
* queryFn: () =>
|
|
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
|
* ```
|
package/inject-queries.mjs
CHANGED
|
@@ -8,31 +8,129 @@ import { QueriesObserver, QueryClient } from "@tanstack/query-core";
|
|
|
8
8
|
import { assertInInjectionContext, computed, effect, inject, untracked } from "@angular/core";
|
|
9
9
|
// src/inject-queries.ts
|
|
10
10
|
/**
|
|
11
|
-
* Injects
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Injects a signal to fetch a variable number of queries.
|
|
12
|
+
*
|
|
13
|
+
* The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
|
|
14
|
+
* the same query key more than once in the array of query objects may cause some data to be shared between
|
|
15
|
+
* queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
|
|
16
|
+
* structure.
|
|
17
|
+
*
|
|
18
|
+
* The `combine` option can be used to combine the results of the queries into a single value.
|
|
19
|
+
* @param optionsFn - A function returning the queries' options — an array of query option objects under
|
|
20
|
+
* `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
|
|
21
|
+
* reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
|
|
22
|
+
* @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
|
|
23
|
+
* results, in the same order as the input. When `combine` is provided, this is the value returned by
|
|
24
|
+
* `combine` instead.
|
|
25
|
+
* @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
|
|
26
|
+
* from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
|
|
27
|
+
* the `select` parameter of a query object written inline cannot be contextually typed from that same
|
|
28
|
+
* object's `queryFn`, so it falls back to `unknown` — a
|
|
29
|
+
* [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
|
|
30
|
+
* parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
|
|
31
|
+
* object _before_ it reaches `injectQueries`, to work around this — see the example below.
|
|
15
32
|
* @see https://tanstack.com/query/latest/docs/framework/angular/guides/parallel-queries
|
|
16
33
|
* @example
|
|
17
34
|
* ```angular-ts
|
|
18
35
|
* @Component({
|
|
19
|
-
* selector: '
|
|
36
|
+
* selector: 'posts',
|
|
20
37
|
* template: `
|
|
21
|
-
*
|
|
22
|
-
* @
|
|
23
|
-
*
|
|
38
|
+
* <ul>
|
|
39
|
+
* @for (query of postQueries(); track $index) {
|
|
40
|
+
* @if (query.isPending()) {
|
|
41
|
+
* <li>Loading...</li>
|
|
42
|
+
* } @else if (query.isError()) {
|
|
43
|
+
* <li>Error: {{ query.error()?.message }}</li>
|
|
44
|
+
* } @else {
|
|
45
|
+
* <li>{{ query.data().title }}</li>
|
|
46
|
+
* }
|
|
24
47
|
* }
|
|
48
|
+
* </ul>
|
|
49
|
+
* `,
|
|
50
|
+
* })
|
|
51
|
+
* export class Posts {
|
|
52
|
+
* readonly ids = signal([1, 2, 3])
|
|
53
|
+
*
|
|
54
|
+
* readonly postQueries = injectQueries(() => ({
|
|
55
|
+
* queries: this.ids().map((id) => ({
|
|
56
|
+
* queryKey: ['post', id],
|
|
57
|
+
* queryFn: () => fetchPost(id),
|
|
58
|
+
* staleTime: Infinity,
|
|
59
|
+
* })),
|
|
60
|
+
* }))
|
|
61
|
+
* }
|
|
62
|
+
* ```
|
|
63
|
+
* @example
|
|
64
|
+
* Combining results into a single value:
|
|
65
|
+
* ```angular-ts
|
|
66
|
+
* @Component({
|
|
67
|
+
* selector: 'posts',
|
|
68
|
+
* template: `
|
|
69
|
+
* @if (combined().isPending) {
|
|
70
|
+
* Loading...
|
|
71
|
+
* } @else if (combined().isError) {
|
|
72
|
+
* Error loading posts
|
|
73
|
+
* } @else {
|
|
74
|
+
* <ul>
|
|
75
|
+
* @for (post of combined().data; track post?.id) {
|
|
76
|
+
* <li>{{ post?.title }}</li>
|
|
77
|
+
* }
|
|
78
|
+
* </ul>
|
|
25
79
|
* }
|
|
26
80
|
* `,
|
|
27
81
|
* })
|
|
28
|
-
* export class
|
|
29
|
-
* readonly
|
|
82
|
+
* export class Posts {
|
|
83
|
+
* readonly ids = signal([1, 2, 3])
|
|
30
84
|
*
|
|
31
|
-
* readonly
|
|
32
|
-
* queries: this.
|
|
33
|
-
* queryKey: ['
|
|
34
|
-
* queryFn: () =>
|
|
85
|
+
* readonly combined = injectQueries(() => ({
|
|
86
|
+
* queries: this.ids().map((id) => ({
|
|
87
|
+
* queryKey: ['post', id],
|
|
88
|
+
* queryFn: () => fetchPost(id),
|
|
35
89
|
* })),
|
|
90
|
+
* combine: (postQueries) => ({
|
|
91
|
+
* data: postQueries.map((query) => query.data),
|
|
92
|
+
* isPending: postQueries.some((query) => query.isPending),
|
|
93
|
+
* isError: postQueries.some((query) => query.isError),
|
|
94
|
+
* }),
|
|
95
|
+
* }))
|
|
96
|
+
* }
|
|
97
|
+
* ```
|
|
98
|
+
* @example
|
|
99
|
+
* Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
|
|
100
|
+
* `select` inline still falls back to `unknown` — wrap the spread in `queryOptions` again so the override is
|
|
101
|
+
* resolved before it reaches `injectQueries`:
|
|
102
|
+
* ```angular-ts
|
|
103
|
+
* const postOptions = (id: number) =>
|
|
104
|
+
* queryOptions({
|
|
105
|
+
* queryKey: ['post', id],
|
|
106
|
+
* queryFn: () => fetchPost(id),
|
|
107
|
+
* })
|
|
108
|
+
*
|
|
109
|
+
* @Component({
|
|
110
|
+
* selector: 'post-title',
|
|
111
|
+
* template: `<h1>{{ fixed()[0].data() }}</h1>`,
|
|
112
|
+
* })
|
|
113
|
+
* export class PostTitle {
|
|
114
|
+
* readonly id = signal(1)
|
|
115
|
+
*
|
|
116
|
+
* readonly broken = injectQueries(() => ({
|
|
117
|
+
* queries: [
|
|
118
|
+
* {
|
|
119
|
+
* ...postOptions(this.id()),
|
|
120
|
+
* // ❌ `data` is `unknown` here
|
|
121
|
+
* select: (data) => data.title,
|
|
122
|
+
* },
|
|
123
|
+
* ],
|
|
124
|
+
* }))
|
|
125
|
+
*
|
|
126
|
+
* readonly fixed = injectQueries(() => ({
|
|
127
|
+
* queries: [
|
|
128
|
+
* queryOptions({
|
|
129
|
+
* ...postOptions(this.id()),
|
|
130
|
+
* // ✅ `data` is `Post`
|
|
131
|
+
* select: (data) => data.title,
|
|
132
|
+
* }),
|
|
133
|
+
* ],
|
|
36
134
|
* }))
|
|
37
135
|
* }
|
|
38
136
|
* ```
|