@tanstack/angular-query 5.0.0-rc.5 → 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/README.md +1 -1
- package/hydration-state-key.mjs +1 -2
- package/index.d.ts +1 -1
- package/index.mjs +1 -2
- package/index.mjs.map +1 -1
- package/infinite-query-options.d.ts +15 -13
- package/infinite-query-options.mjs +1 -2
- package/infinite-query-options.mjs.map +1 -1
- package/inject-base-query.mjs +3 -4
- package/inject-base-query.mjs.map +1 -1
- package/inject-infinite-query.d.ts +170 -33
- package/inject-infinite-query.mjs +2 -3
- package/inject-infinite-query.mjs.map +1 -1
- package/inject-is-fetching.d.ts +37 -6
- package/inject-is-fetching.mjs +36 -6
- package/inject-is-fetching.mjs.map +1 -1
- package/inject-is-mutating.d.ts +21 -6
- package/inject-is-mutating.mjs +20 -6
- package/inject-is-mutating.mjs.map +1 -1
- package/inject-is-restoring.d.ts +5 -3
- package/inject-is-restoring.mjs +6 -5
- package/inject-is-restoring.mjs.map +1 -1
- package/inject-mutation-state.d.ts +51 -3
- package/inject-mutation-state.mjs +52 -5
- package/inject-mutation-state.mjs.map +1 -1
- package/inject-mutation.d.ts +118 -13
- package/inject-mutation.mjs +121 -17
- package/inject-mutation.mjs.map +1 -1
- package/inject-queries.d.ts +113 -15
- package/inject-queries.mjs +116 -19
- package/inject-queries.mjs.map +1 -1
- package/inject-queries.types.d.ts +25 -5
- package/inject-query.d.ts +11 -8
- package/inject-query.mjs +2 -3
- package/inject-query.mjs.map +1 -1
- package/mutation-options.mjs +1 -2
- package/package.json +2 -2
- package/providers.d.ts +31 -6
- package/providers.mjs +32 -8
- package/providers.mjs.map +1 -1
- package/query-options.d.ts +23 -13
- package/query-options.mjs +1 -2
- package/query-options.mjs.map +1 -1
- package/query-resource.d.ts +4 -1
- package/query-resource.mjs +4 -2
- package/query-resource.mjs.map +1 -1
- package/schematics/migrate-from-experimental/index.js +3 -3
- package/schematics/migrate-from-experimental/workspace.js +1 -1
- package/schematics/ng-add/index.js +5 -4
- package/types.d.ts +38 -7
- package/utils/inject-external-store.mjs +1 -2
- package/utils/inject-pending-tasks-lifecycle.mjs +1 -2
- package/utils/inject-query-zone.mjs +1 -2
- package/utils/result-fields.mjs +1 -2
- package/utils/signal-proxy.mjs +1 -2
package/inject-is-fetching.mjs
CHANGED
|
@@ -1,14 +1,45 @@
|
|
|
1
1
|
import { injectExternalStore } from "./utils/inject-external-store.mjs";
|
|
2
2
|
import { QueryClient } from "@tanstack/query-core";
|
|
3
3
|
import { assertInInjectionContext, inject } from "@angular/core";
|
|
4
|
-
|
|
4
|
+
// src/inject-is-fetching.ts
|
|
5
5
|
/**
|
|
6
6
|
* Injects a signal that tracks the number of queries that your application is loading or fetching in the
|
|
7
7
|
* background (useful for app-wide loading indicators).
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* @returns
|
|
8
|
+
* @param filters - A function returning the {@link QueryFilters} to narrow down the matched queries. Similar
|
|
9
|
+
* to `computed` from Angular, this function runs in the reactive context, so signals read inside it
|
|
10
|
+
* re-narrow the matched queries.
|
|
11
|
+
* @returns A `Signal` with the number of queries that your application is currently loading or fetching in
|
|
12
|
+
* the background.
|
|
13
|
+
* @example
|
|
14
|
+
* ```angular-ts
|
|
15
|
+
* @Component({
|
|
16
|
+
* selector: 'posts-fetching-indicator',
|
|
17
|
+
* template: `
|
|
18
|
+
* @if (isFetchingPosts()) {
|
|
19
|
+
* <span>Refreshing posts...</span>
|
|
20
|
+
* }
|
|
21
|
+
* `,
|
|
22
|
+
* })
|
|
23
|
+
* export class PostsFetchingIndicator {
|
|
24
|
+
* // How many queries matching the posts prefix are fetching?
|
|
25
|
+
* readonly isFetchingPosts = injectIsFetching(() => ({ queryKey: ['posts'] }))
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
* @example
|
|
29
|
+
* A global loading indicator for any query fetching in the background, not just the ones on screen:
|
|
30
|
+
* ```angular-ts
|
|
31
|
+
* @Component({
|
|
32
|
+
* selector: 'global-loading-indicator',
|
|
33
|
+
* template: `
|
|
34
|
+
* @if (isFetching()) {
|
|
35
|
+
* <div>Queries are fetching in the background...</div>
|
|
36
|
+
* }
|
|
37
|
+
* `,
|
|
38
|
+
* })
|
|
39
|
+
* export class GlobalLoadingIndicator {
|
|
40
|
+
* readonly isFetching = injectIsFetching()
|
|
41
|
+
* }
|
|
42
|
+
* ```
|
|
12
43
|
*/
|
|
13
44
|
function injectIsFetching(filters = () => ({})) {
|
|
14
45
|
if (typeof ngDevMode === "undefined" || ngDevMode) assertInInjectionContext(injectIsFetching);
|
|
@@ -19,7 +50,6 @@ function injectIsFetching(filters = () => ({})) {
|
|
|
19
50
|
subscribe: (onStoreChange) => cache.subscribe(onStoreChange)
|
|
20
51
|
}));
|
|
21
52
|
}
|
|
22
|
-
//#endregion
|
|
23
53
|
export { injectIsFetching };
|
|
24
54
|
|
|
25
55
|
//# sourceMappingURL=inject-is-fetching.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-is-fetching.mjs","names":[],"sources":["../src/inject-is-fetching.ts"],"sourcesContent":["import { assertInInjectionContext, inject } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport type {
|
|
1
|
+
{"version":3,"file":"inject-is-fetching.mjs","names":[],"sources":["../src/inject-is-fetching.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 { QueryFilters } from '@tanstack/query-core'\n\n/**\n * Injects a signal that tracks the number of queries that your application is loading or fetching in the\n * background (useful for app-wide loading indicators).\n * @param filters - A function returning the {@link QueryFilters} to narrow down the matched queries. Similar\n * to `computed` from Angular, this function runs in the reactive context, so signals read inside it\n * re-narrow the matched queries.\n * @returns A `Signal` with the number of queries that your application is currently loading or fetching in\n * the background.\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts-fetching-indicator',\n * template: `\n * @if (isFetchingPosts()) {\n * <span>Refreshing posts...</span>\n * }\n * `,\n * })\n * export class PostsFetchingIndicator {\n * // How many queries matching the posts prefix are fetching?\n * readonly isFetchingPosts = injectIsFetching(() => ({ queryKey: ['posts'] }))\n * }\n * ```\n * @example\n * A global loading indicator for any query fetching in the background, not just the ones on screen:\n * ```angular-ts\n * @Component({\n * selector: 'global-loading-indicator',\n * template: `\n * @if (isFetching()) {\n * <div>Queries are fetching in the background...</div>\n * }\n * `,\n * })\n * export class GlobalLoadingIndicator {\n * readonly isFetching = injectIsFetching()\n * }\n * ```\n */\nexport function injectIsFetching(\n filters: () => Omit<QueryFilters, 'fetchStatus'> = () => ({}),\n): Signal<number> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectIsFetching)\n }\n const queryClient = inject(QueryClient)\n const cache = queryClient.getQueryCache()\n\n return injectExternalStore(() => ({\n getSnapshot: () => queryClient.isFetching(filters()),\n subscribe: (onStoreChange) => cache.subscribe(onStoreChange),\n }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,SAAgB,iBACd,iBAA0D,CAAC,IAC3C;CAChB,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,gBAAgB;CAE3C,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,QAAQ,YAAY,cAAc;CAExC,OAAO,2BAA2B;EAChC,mBAAmB,YAAY,WAAW,QAAQ,CAAC;EACnD,YAAY,kBAAkB,MAAM,UAAU,aAAa;CAC7D,EAAE;AACJ"}
|
package/inject-is-mutating.d.ts
CHANGED
|
@@ -1,11 +1,26 @@
|
|
|
1
|
-
import { MutationFilters } from '@tanstack/query-core';
|
|
2
1
|
import { Signal } from '@angular/core';
|
|
2
|
+
import { MutationFilters } from '@tanstack/query-core';
|
|
3
3
|
/**
|
|
4
4
|
* Injects a signal that tracks the number of mutations that your application currently has `pending`
|
|
5
5
|
* (useful for app-wide loading indicators).
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* @returns A
|
|
6
|
+
* @param filters - A function returning the {@link MutationFilters} to narrow down the matched mutations.
|
|
7
|
+
* Similar to `computed` from Angular, this function runs in the reactive context, so signals read inside it
|
|
8
|
+
* re-narrow the matched mutations.
|
|
9
|
+
* @returns A `Signal` with the number of mutations that your application currently has `pending`.
|
|
10
|
+
* @example
|
|
11
|
+
* ```angular-ts
|
|
12
|
+
* @Component({
|
|
13
|
+
* selector: 'posts-mutating-indicator',
|
|
14
|
+
* template: `
|
|
15
|
+
* @if (isMutatingPosts()) {
|
|
16
|
+
* <span>Saving posts...</span>
|
|
17
|
+
* }
|
|
18
|
+
* `,
|
|
19
|
+
* })
|
|
20
|
+
* export class PostsMutatingIndicator {
|
|
21
|
+
* // How many mutations matching the posts prefix are in progress?
|
|
22
|
+
* readonly isMutatingPosts = injectIsMutating(() => ({ mutationKey: ['posts'] }))
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
10
25
|
*/
|
|
11
|
-
export declare function injectIsMutating(filters?: () => MutationFilters): Signal<number>;
|
|
26
|
+
export declare function injectIsMutating(filters?: () => Omit<MutationFilters, 'status'>): Signal<number>;
|
package/inject-is-mutating.mjs
CHANGED
|
@@ -1,14 +1,29 @@
|
|
|
1
1
|
import { injectExternalStore } from "./utils/inject-external-store.mjs";
|
|
2
2
|
import { QueryClient } from "@tanstack/query-core";
|
|
3
3
|
import { assertInInjectionContext, inject } from "@angular/core";
|
|
4
|
-
|
|
4
|
+
// src/inject-is-mutating.ts
|
|
5
5
|
/**
|
|
6
6
|
* Injects a signal that tracks the number of mutations that your application currently has `pending`
|
|
7
7
|
* (useful for app-wide loading indicators).
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* @returns A
|
|
8
|
+
* @param filters - A function returning the {@link MutationFilters} to narrow down the matched mutations.
|
|
9
|
+
* Similar to `computed` from Angular, this function runs in the reactive context, so signals read inside it
|
|
10
|
+
* re-narrow the matched mutations.
|
|
11
|
+
* @returns A `Signal` with the number of mutations that your application currently has `pending`.
|
|
12
|
+
* @example
|
|
13
|
+
* ```angular-ts
|
|
14
|
+
* @Component({
|
|
15
|
+
* selector: 'posts-mutating-indicator',
|
|
16
|
+
* template: `
|
|
17
|
+
* @if (isMutatingPosts()) {
|
|
18
|
+
* <span>Saving posts...</span>
|
|
19
|
+
* }
|
|
20
|
+
* `,
|
|
21
|
+
* })
|
|
22
|
+
* export class PostsMutatingIndicator {
|
|
23
|
+
* // How many mutations matching the posts prefix are in progress?
|
|
24
|
+
* readonly isMutatingPosts = injectIsMutating(() => ({ mutationKey: ['posts'] }))
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
12
27
|
*/
|
|
13
28
|
function injectIsMutating(filters = () => ({})) {
|
|
14
29
|
if (typeof ngDevMode === "undefined" || ngDevMode) assertInInjectionContext(injectIsMutating);
|
|
@@ -19,7 +34,6 @@ function injectIsMutating(filters = () => ({})) {
|
|
|
19
34
|
subscribe: (onStoreChange) => cache.subscribe(onStoreChange)
|
|
20
35
|
}));
|
|
21
36
|
}
|
|
22
|
-
//#endregion
|
|
23
37
|
export { injectIsMutating };
|
|
24
38
|
|
|
25
39
|
//# sourceMappingURL=inject-is-mutating.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-is-mutating.mjs","names":[],"sources":["../src/inject-is-mutating.ts"],"sourcesContent":["import { assertInInjectionContext, inject } from '@angular/core'\nimport { QueryClient } from '@tanstack/query-core'\nimport { injectExternalStore } from './utils/inject-external-store'\nimport type {
|
|
1
|
+
{"version":3,"file":"inject-is-mutating.mjs","names":[],"sources":["../src/inject-is-mutating.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 { MutationFilters } from '@tanstack/query-core'\n\n/**\n * Injects a signal that tracks the number of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - A function returning the {@link MutationFilters} to narrow down the matched mutations.\n * Similar to `computed` from Angular, this function runs in the reactive context, so signals read inside it\n * re-narrow the matched mutations.\n * @returns A `Signal` with the number of mutations that your application currently has `pending`.\n * @example\n * ```angular-ts\n * @Component({\n * selector: 'posts-mutating-indicator',\n * template: `\n * @if (isMutatingPosts()) {\n * <span>Saving posts...</span>\n * }\n * `,\n * })\n * export class PostsMutatingIndicator {\n * // How many mutations matching the posts prefix are in progress?\n * readonly isMutatingPosts = injectIsMutating(() => ({ mutationKey: ['posts'] }))\n * }\n * ```\n */\nexport function injectIsMutating(\n filters: () => Omit<MutationFilters, 'status'> = () => ({}),\n): Signal<number> {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectIsMutating)\n }\n const queryClient = inject(QueryClient)\n const cache = queryClient.getMutationCache()\n\n return injectExternalStore(() => ({\n getSnapshot: () => queryClient.isMutating(filters()),\n subscribe: (onStoreChange) => cache.subscribe(onStoreChange),\n }))\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,iBACd,iBAAwD,CAAC,IACzC;CAChB,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,gBAAgB;CAE3C,MAAM,cAAc,OAAO,WAAW;CACtC,MAAM,QAAQ,YAAY,iBAAiB;CAE3C,OAAO,2BAA2B;EAChC,mBAAmB,YAAY,WAAW,QAAQ,CAAC;EACnD,YAAY,kBAAkB,MAAM,UAAU,aAAa;CAC7D,EAAE;AACJ"}
|
package/inject-is-restoring.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { Provider, Signal } from '@angular/core';
|
|
2
2
|
/**
|
|
3
|
-
* Injects a
|
|
4
|
-
*
|
|
5
|
-
*
|
|
3
|
+
* Injects a signal that tracks whether a restore (e.g. from a persisted client, wired up via
|
|
4
|
+
* `withPersistQueryClient`) is currently in progress. `injectQuery` and friends also check this internally
|
|
5
|
+
* to avoid race conditions between the restore and initializing queries.
|
|
6
|
+
* @returns A readonly `Signal<boolean>` — `true` while a restore is in progress, `false` otherwise (the
|
|
7
|
+
* default when no persistence integration is registered).
|
|
6
8
|
*/
|
|
7
9
|
export declare function injectIsRestoring(): Signal<boolean>;
|
|
8
10
|
/**
|
package/inject-is-restoring.mjs
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { InjectionToken, assertInInjectionContext, inject, signal } from "@angular/core";
|
|
2
|
-
|
|
2
|
+
// src/inject-is-restoring.ts
|
|
3
3
|
/**
|
|
4
4
|
* Internal token used to track isRestoring state, accessible in public API through `injectIsRestoring` and set via `provideIsRestoring`
|
|
5
5
|
*/
|
|
6
6
|
var IS_RESTORING = new InjectionToken("", { factory: () => signal(false).asReadonly() });
|
|
7
7
|
/**
|
|
8
|
-
* Injects a
|
|
9
|
-
*
|
|
10
|
-
*
|
|
8
|
+
* Injects a signal that tracks whether a restore (e.g. from a persisted client, wired up via
|
|
9
|
+
* `withPersistQueryClient`) is currently in progress. `injectQuery` and friends also check this internally
|
|
10
|
+
* to avoid race conditions between the restore and initializing queries.
|
|
11
|
+
* @returns A readonly `Signal<boolean>` — `true` while a restore is in progress, `false` otherwise (the
|
|
12
|
+
* default when no persistence integration is registered).
|
|
11
13
|
*/
|
|
12
14
|
function injectIsRestoring() {
|
|
13
15
|
if (typeof ngDevMode === "undefined" || ngDevMode) assertInInjectionContext(injectIsRestoring);
|
|
@@ -26,7 +28,6 @@ function provideIsRestoring(isRestoringFactory) {
|
|
|
26
28
|
useFactory: isRestoringFactory
|
|
27
29
|
};
|
|
28
30
|
}
|
|
29
|
-
//#endregion
|
|
30
31
|
export { injectIsRestoring, provideIsRestoring };
|
|
31
32
|
|
|
32
33
|
//# sourceMappingURL=inject-is-restoring.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inject-is-restoring.mjs","names":[],"sources":["../src/inject-is-restoring.ts"],"sourcesContent":["import {\n InjectionToken,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport type { Provider, Signal } from '@angular/core'\n\n/**\n * Internal token used to track isRestoring state, accessible in public API through `injectIsRestoring` and set via `provideIsRestoring`\n */\nconst IS_RESTORING = new InjectionToken('', {\n factory: () => signal(false).asReadonly(),\n})\n\n/**\n * Injects a
|
|
1
|
+
{"version":3,"file":"inject-is-restoring.mjs","names":[],"sources":["../src/inject-is-restoring.ts"],"sourcesContent":["import {\n InjectionToken,\n assertInInjectionContext,\n inject,\n signal,\n} from '@angular/core'\nimport type { Provider, Signal } from '@angular/core'\n\n/**\n * Internal token used to track isRestoring state, accessible in public API through `injectIsRestoring` and set via `provideIsRestoring`\n */\nconst IS_RESTORING = new InjectionToken('', {\n factory: () => signal(false).asReadonly(),\n})\n\n/**\n * Injects a signal that tracks whether a restore (e.g. from a persisted client, wired up via\n * `withPersistQueryClient`) is currently in progress. `injectQuery` and friends also check this internally\n * to avoid race conditions between the restore and initializing queries.\n * @returns A readonly `Signal<boolean>` — `true` while a restore is in progress, `false` otherwise (the\n * default when no persistence integration is registered).\n */\nexport function injectIsRestoring() {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertInInjectionContext(injectIsRestoring)\n }\n return inject(IS_RESTORING)\n}\n\n/**\n * Supplies injector-scoped restoration state to the Angular Query integrations.\n * The factory runs once in Angular's injection context.\n * @internal\n * @param isRestoringFactory - Produces the restoration signal for this injector.\n * @returns The provider that makes the restoration state injectable.\n */\nexport function provideIsRestoring(\n isRestoringFactory: () => Signal<boolean>,\n): Provider {\n return {\n provide: IS_RESTORING,\n useFactory: isRestoringFactory,\n }\n}\n"],"mappings":";;;;;AAWA,IAAM,eAAe,IAAI,eAAe,IAAI,EAC1C,eAAe,OAAO,KAAK,CAAC,CAAC,WAAW,EAC1C,CAAC;;;;;;;;AASD,SAAgB,oBAAoB;CAClC,IAAI,OAAO,cAAc,eAAe,WACtC,yBAAyB,iBAAiB;CAE5C,OAAO,OAAO,YAAY;AAC5B;;;;;;;;AASA,SAAgB,mBACd,oBACU;CACV,OAAO;EACL,SAAS;EACT,YAAY;CACd;AACF"}
|
|
@@ -17,9 +17,57 @@ export type MutationStateOptions<TResult = MutationState, TMutation extends Muta
|
|
|
17
17
|
select?: (mutation: TMutation) => TResult;
|
|
18
18
|
};
|
|
19
19
|
/**
|
|
20
|
-
* Injects a signal that
|
|
21
|
-
* @
|
|
22
|
-
* @
|
|
20
|
+
* Injects a signal that gives you access to all mutations in the `MutationCache`. You can pass `filters`
|
|
21
|
+
* ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation state.
|
|
22
|
+
* @param options - A function returning the `filters` to narrow down matched mutations, and an optional
|
|
23
|
+
* `select` to transform the mutation state. Similar to `computed` from Angular, this function runs in the
|
|
24
|
+
* reactive context, so signals read inside it re-narrow the matched mutations.
|
|
25
|
+
* @returns A `Signal` with an Array of whatever `select` returns for each matching mutation.
|
|
26
|
+
* @example
|
|
27
|
+
* Get all variables of all running mutations:
|
|
28
|
+
* ```angular-ts
|
|
29
|
+
* @Component({
|
|
30
|
+
* selector: 'pending-posts',
|
|
31
|
+
* template: `{{ pendingVariables().length }} posts saving...`,
|
|
32
|
+
* })
|
|
33
|
+
* export class PendingPosts {
|
|
34
|
+
* readonly pendingVariables = injectMutationState(() => ({
|
|
35
|
+
* filters: { status: 'pending' },
|
|
36
|
+
* select: (mutation) => mutation.state.variables,
|
|
37
|
+
* }))
|
|
38
|
+
* }
|
|
39
|
+
* ```
|
|
40
|
+
* @example
|
|
41
|
+
* Get all data for specific mutations via the `mutationKey`:
|
|
42
|
+
* ```angular-ts
|
|
43
|
+
* const mutationKey = ['posts']
|
|
44
|
+
*
|
|
45
|
+
* @Component({
|
|
46
|
+
* selector: 'posts',
|
|
47
|
+
* template: `
|
|
48
|
+
* <button (click)="createPost()">
|
|
49
|
+
* Create post ({{ savedPosts().length }} saved so far)
|
|
50
|
+
* </button>
|
|
51
|
+
* `,
|
|
52
|
+
* })
|
|
53
|
+
* export class Posts {
|
|
54
|
+
* // Some mutation that we want to get the state for
|
|
55
|
+
* readonly createPostMutation = injectMutation(() => ({
|
|
56
|
+
* mutationKey,
|
|
57
|
+
* mutationFn: createPosts,
|
|
58
|
+
* }))
|
|
59
|
+
*
|
|
60
|
+
* readonly savedPosts = injectMutationState(() => ({
|
|
61
|
+
* // this mutation key needs to match the mutation key of the given mutation (see above)
|
|
62
|
+
* filters: { mutationKey, status: 'success' },
|
|
63
|
+
* select: (mutation) => mutation.state.data,
|
|
64
|
+
* }))
|
|
65
|
+
*
|
|
66
|
+
* createPost() {
|
|
67
|
+
* this.createPostMutation.mutate(['New Post'])
|
|
68
|
+
* }
|
|
69
|
+
* }
|
|
70
|
+
* ```
|
|
23
71
|
*/
|
|
24
72
|
export declare function injectMutationState<TResult = MutationState, TMutation extends Mutation<any, any, any, any> = MutationTypeFromResult<TResult>>(options?: () => MutationStateOptions<TResult, TMutation>): Signal<Array<TResult>>;
|
|
25
73
|
export {};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { injectExternalStore } from "./utils/inject-external-store.mjs";
|
|
2
2
|
import { QueryClient } from "@tanstack/query-core";
|
|
3
3
|
import { assertInInjectionContext, inject } from "@angular/core";
|
|
4
|
-
|
|
4
|
+
// src/inject-mutation-state.ts
|
|
5
5
|
/**
|
|
6
6
|
* Reads and projects the matching entries in a mutation cache.
|
|
7
7
|
* @param mutationCache - The cache to inspect.
|
|
@@ -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
|
|
16
|
-
* @
|
|
17
|
-
* @
|
|
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);
|
|
@@ -24,7 +72,6 @@ function injectMutationState(options = () => ({})) {
|
|
|
24
72
|
subscribe: (onStoreChange) => mutationCache.subscribe(onStoreChange)
|
|
25
73
|
}), { equal: (previous, next) => previous.length === next.length && previous.every((value, index) => Object.is(value, next[index])) });
|
|
26
74
|
}
|
|
27
|
-
//#endregion
|
|
28
75
|
export { injectMutationState };
|
|
29
76
|
|
|
30
77
|
//# sourceMappingURL=inject-mutation-state.mjs.map
|
|
@@ -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>;
|