@tanstack/react-query 5.104.3 → 5.104.5

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.
@@ -14,7 +14,7 @@ let _tanstack_query_core = require("@tanstack/query-core");
14
14
  * @param query - The query, used to evaluate a `throwOnError` function against its error.
15
15
  */
16
16
  const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
17
- const throwOnError = (query === null || query === void 0 ? void 0 : query.state.error) && typeof options.throwOnError === "function" ? (0, _tanstack_query_core.shouldThrowError)(options.throwOnError, [query.state.error, query]) : options.throwOnError;
17
+ const throwOnError = (query === null || query === void 0 ? void 0 : query.state.status) === "error" && typeof options.throwOnError === "function" ? (0, _tanstack_query_core.shouldThrowError)(options.throwOnError, [query.state.error, query]) : options.throwOnError;
18
18
  if (options.suspense || throwOnError) {
19
19
  if (!errorResetBoundary.isReset()) options.retryOnMount = false;
20
20
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.cjs","names":["shouldThrowError"],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.error && typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [query.state.error, query])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,gBAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IACJ,MAAO,MAAM,UAAS,OAAO,QAAQ,iBAAiB,cAAA,GAClDA,qBAAAA,iBAAAA,CAAiB,QAAQ,cAAc,CAAC,MAAM,MAAM,OAAO,KAAK,CAAC,IACjE,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,MAAA,GAC5BA,qBAAAA,iBAAAA,CAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
1
+ {"version":3,"file":"errorBoundaryUtils.cjs","names":["shouldThrowError"],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.status === 'error' &&\n typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [\n query.state.error as TError,\n query,\n ])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,gBAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IACJ,MAAO,MAAM,YAAW,WACxB,OAAO,QAAQ,iBAAiB,cAAA,GAC5BA,qBAAAA,iBAAAA,CAAiB,QAAQ,cAAc,CACrC,MAAM,MAAM,OACZ,KACF,CAAC,IACD,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,MAAA,GAC5BA,qBAAAA,iBAAAA,CAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.d.cts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAoBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
1
+ {"version":3,"file":"errorBoundaryUtils.d.cts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAwBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.d.ts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAoBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
1
+ {"version":3,"file":"errorBoundaryUtils.d.ts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAwBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
@@ -11,7 +11,7 @@ import { shouldThrowError } from "@tanstack/query-core";
11
11
  * @param query - The query, used to evaluate a `throwOnError` function against its error.
12
12
  */
13
13
  const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
14
- const throwOnError = (query === null || query === void 0 ? void 0 : query.state.error) && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
14
+ const throwOnError = (query === null || query === void 0 ? void 0 : query.state.status) === "error" && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
15
15
  if (options.suspense || throwOnError) {
16
16
  if (!errorResetBoundary.isReset()) options.retryOnMount = false;
17
17
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.js","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.error && typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [query.state.error, query])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,gBAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IACJ,MAAO,MAAM,UAAS,OAAO,QAAQ,iBAAiB,aAClD,iBAAiB,QAAQ,cAAc,CAAC,MAAM,MAAM,OAAO,KAAK,CAAC,IACjE,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,KAC5B,iBAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
1
+ {"version":3,"file":"errorBoundaryUtils.js","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.status === 'error' &&\n typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [\n query.state.error as TError,\n query,\n ])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,gBAAA,UAAA,QAAA,UAAA,KAAA,IAAA,KAAA,IACJ,MAAO,MAAM,YAAW,WACxB,OAAO,QAAQ,iBAAiB,aAC5B,iBAAiB,QAAQ,cAAc,CACrC,MAAM,MAAM,OACZ,KACF,CAAC,IACD,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,KAC5B,iBAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
@@ -33,14 +33,27 @@ function useIsMutating(filters, queryClient) {
33
33
  } }, client).length;
34
34
  }
35
35
  /**
36
- * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
37
- * (or to their state, by default).
38
- * @param mutationCache - The mutation cache to read.
39
- * @param options - The `filters` to match and the `select` function to map each mutation with.
40
- * @returns The selected value of every matching mutation.
36
+ * Creates snapshot getters that share equal selected results across renders.
37
+ * A new getter is created on each render. Each getter caches its snapshot until the matching mutations
38
+ * or their states change.
39
+ * @returns A factory for snapshot getters with a shared result cache.
41
40
  */
42
- function getResult(mutationCache, options) {
43
- return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
41
+ function createSnapshotFactory() {
42
+ let previousResult;
43
+ return (mutationCache, options) => {
44
+ let inputs = [];
45
+ let snapshot;
46
+ return () => {
47
+ const mutations = mutationCache.findAll(options.filters);
48
+ const nextInputs = mutations.flatMap((mutation) => [mutation, mutation.state]);
49
+ if (!snapshot || nextInputs.length !== inputs.length || nextInputs.some((input, index) => !Object.is(input, inputs[index]))) {
50
+ inputs = nextInputs;
51
+ snapshot = (0, _tanstack_query_core.replaceEqualDeep)(previousResult, mutations.map((mutation) => options.select ? options.select(mutation) : mutation.state));
52
+ previousResult = snapshot;
53
+ }
54
+ return snapshot;
55
+ };
56
+ };
44
57
  }
45
58
  /**
46
59
  * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
@@ -113,19 +126,9 @@ function getResult(mutationCache, options) {
113
126
  */
114
127
  function useMutationState(options = {}, queryClient) {
115
128
  const mutationCache = require_QueryClientProvider.useQueryClient(queryClient).getMutationCache();
116
- const optionsRef = react.useRef(options);
117
- const resultRef = react.useRef(null);
118
- if (resultRef.current === null) resultRef.current = getResult(mutationCache, options);
119
- react.useEffect(() => {
120
- optionsRef.current = options;
121
- });
122
- return react.useSyncExternalStore(react.useCallback((onStoreChange) => mutationCache.subscribe(() => {
123
- const nextResult = (0, _tanstack_query_core.replaceEqualDeep)(resultRef.current, getResult(mutationCache, optionsRef.current));
124
- if (resultRef.current !== nextResult) {
125
- resultRef.current = nextResult;
126
- _tanstack_query_core.notifyManager.schedule(onStoreChange);
127
- }
128
- }), [mutationCache]), () => resultRef.current, () => resultRef.current);
129
+ const [createSnapshot] = react.useState(() => createSnapshotFactory());
130
+ const getSnapshot = createSnapshot(mutationCache, options);
131
+ return react.useSyncExternalStore(react.useCallback((onStoreChange) => mutationCache.subscribe(_tanstack_query_core.notifyManager.batchCalls(onStoreChange)), [mutationCache]), getSnapshot, getSnapshot);
129
132
  }
130
133
  //#endregion
131
134
  exports.useIsMutating = useIsMutating;
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","React","replaceEqualDeep"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`\n * (or to their state, by default).\n * @param mutationCache - The mutation cache to read.\n * @param options - The `filters` to match and the `select` function to map each mutation with.\n * @returns The selected value of every matching mutation.\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 * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const optionsRef = React.useRef(options)\n const resultRef = React.useRef<Array<TResult>>(null)\n if (resultRef.current === null) {\n resultRef.current = getResult(mutationCache, options)\n }\n\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(() => {\n const nextResult = replaceEqualDeep(\n resultRef.current,\n getResult(mutationCache, optionsRef.current),\n )\n if (resultRef.current !== nextResult) {\n resultRef.current = nextResult\n notifyManager.schedule(onStoreChange)\n }\n }),\n [mutationCache],\n ),\n () => resultRef.current,\n () => resultRef.current,\n )!\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;;AA6BA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBA,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,aAAaC,MAAM,OAAO,OAAO;CACvC,MAAM,YAAYA,MAAM,OAAuB,IAAI;CACnD,IAAI,UAAU,YAAY,MACxB,UAAU,UAAU,UAAU,eAAe,OAAO;CAGtD,MAAM,gBAAgB;EACpB,WAAW,UAAU;CACvB,CAAC;CAED,OAAOA,MAAM,qBACXA,MAAM,aACH,kBACC,cAAc,gBAAgB;EAC5B,MAAM,cAAA,GAAaC,qBAAAA,iBAAAA,CACjB,UAAU,SACV,UAAU,eAAe,WAAW,OAAO,CAC7C;EACA,IAAI,UAAU,YAAY,YAAY;GACpC,UAAU,UAAU;GACpB,qBAAA,cAAc,SAAS,aAAa;EACtC;CACF,CAAC,GACH,CAAC,aAAa,CAChB,SACM,UAAU,eACV,UAAU,OAClB;AACF"}
1
+ {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","replaceEqualDeep","React","notifyManager"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Creates snapshot getters that share equal selected results across renders.\n * A new getter is created on each render. Each getter caches its snapshot until the matching mutations\n * or their states change.\n * @returns A factory for snapshot getters with a shared result cache.\n */\nfunction createSnapshotFactory<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>() {\n let previousResult: Array<TResult> | undefined\n\n return (\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n ) => {\n let inputs: Array<unknown> = []\n let snapshot: Array<TResult> | undefined\n\n return (): Array<TResult> => {\n const mutations = mutationCache.findAll(options.filters)\n const nextInputs = mutations.flatMap((mutation) => [\n mutation,\n mutation.state,\n ])\n\n if (\n !snapshot ||\n nextInputs.length !== inputs.length ||\n nextInputs.some((input, index) => !Object.is(input, inputs[index]))\n ) {\n inputs = nextInputs\n snapshot = replaceEqualDeep(\n previousResult,\n mutations.map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n ),\n )\n previousResult = snapshot\n }\n\n return snapshot\n }\n }\n}\n\n/**\n * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const [createSnapshot] = React.useState(() =>\n createSnapshotFactory<TResult, TMutation>(),\n )\n const getSnapshot = createSnapshot(mutationCache, options)\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)),\n [mutationCache],\n ),\n getSnapshot,\n getSnapshot,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;AA4BA,SAAS,wBAIL;CACF,IAAI;CAEJ,QACE,eACA,YACG;EACH,IAAI,SAAyB,CAAC;EAC9B,IAAI;EAEJ,aAA6B;GAC3B,MAAM,YAAY,cAAc,QAAQ,QAAQ,OAAO;GACvD,MAAM,aAAa,UAAU,SAAS,aAAa,CACjD,UACA,SAAS,KACX,CAAC;GAED,IACE,CAAC,YACD,WAAW,WAAW,OAAO,UAC7B,WAAW,MAAM,OAAO,UAAU,CAAC,OAAO,GAAG,OAAO,OAAO,MAAM,CAAC,GAClE;IACA,SAAS;IACT,YAAA,GAAWC,qBAAAA,iBAAAA,CACT,gBACA,UAAU,KACP,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB,CACF;IACA,iBAAiB;GACnB;GAEA,OAAO;EACT;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBD,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,CAAC,kBAAkBE,MAAM,eAC7B,sBAA0C,CAC5C;CACA,MAAM,cAAc,eAAe,eAAe,OAAO;CAEzD,OAAOA,MAAM,qBACXA,MAAM,aACH,kBACC,cAAc,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,GACjE,CAAC,aAAa,CAChB,GACA,aACA,WACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.d.cts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiGpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
1
+ {"version":3,"file":"useMutationState.d.cts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0HpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.d.ts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiGpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
1
+ {"version":3,"file":"useMutationState.d.ts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0HpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
@@ -30,14 +30,27 @@ function useIsMutating(filters, queryClient) {
30
30
  } }, client).length;
31
31
  }
32
32
  /**
33
- * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
34
- * (or to their state, by default).
35
- * @param mutationCache - The mutation cache to read.
36
- * @param options - The `filters` to match and the `select` function to map each mutation with.
37
- * @returns The selected value of every matching mutation.
33
+ * Creates snapshot getters that share equal selected results across renders.
34
+ * A new getter is created on each render. Each getter caches its snapshot until the matching mutations
35
+ * or their states change.
36
+ * @returns A factory for snapshot getters with a shared result cache.
38
37
  */
39
- function getResult(mutationCache, options) {
40
- return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
38
+ function createSnapshotFactory() {
39
+ let previousResult;
40
+ return (mutationCache, options) => {
41
+ let inputs = [];
42
+ let snapshot;
43
+ return () => {
44
+ const mutations = mutationCache.findAll(options.filters);
45
+ const nextInputs = mutations.flatMap((mutation) => [mutation, mutation.state]);
46
+ if (!snapshot || nextInputs.length !== inputs.length || nextInputs.some((input, index) => !Object.is(input, inputs[index]))) {
47
+ inputs = nextInputs;
48
+ snapshot = replaceEqualDeep(previousResult, mutations.map((mutation) => options.select ? options.select(mutation) : mutation.state));
49
+ previousResult = snapshot;
50
+ }
51
+ return snapshot;
52
+ };
53
+ };
41
54
  }
42
55
  /**
43
56
  * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
@@ -110,19 +123,9 @@ function getResult(mutationCache, options) {
110
123
  */
111
124
  function useMutationState(options = {}, queryClient) {
112
125
  const mutationCache = useQueryClient(queryClient).getMutationCache();
113
- const optionsRef = React.useRef(options);
114
- const resultRef = React.useRef(null);
115
- if (resultRef.current === null) resultRef.current = getResult(mutationCache, options);
116
- React.useEffect(() => {
117
- optionsRef.current = options;
118
- });
119
- return React.useSyncExternalStore(React.useCallback((onStoreChange) => mutationCache.subscribe(() => {
120
- const nextResult = replaceEqualDeep(resultRef.current, getResult(mutationCache, optionsRef.current));
121
- if (resultRef.current !== nextResult) {
122
- resultRef.current = nextResult;
123
- notifyManager.schedule(onStoreChange);
124
- }
125
- }), [mutationCache]), () => resultRef.current, () => resultRef.current);
126
+ const [createSnapshot] = React.useState(() => createSnapshotFactory());
127
+ const getSnapshot = createSnapshot(mutationCache, options);
128
+ return React.useSyncExternalStore(React.useCallback((onStoreChange) => mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), [mutationCache]), getSnapshot, getSnapshot);
126
129
  }
127
130
  //#endregion
128
131
  export { useIsMutating, useMutationState };
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.js","names":[],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`\n * (or to their state, by default).\n * @param mutationCache - The mutation cache to read.\n * @param options - The `filters` to match and the `select` function to map each mutation with.\n * @returns The selected value of every matching mutation.\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 * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const optionsRef = React.useRef(options)\n const resultRef = React.useRef<Array<TResult>>(null)\n if (resultRef.current === null) {\n resultRef.current = getResult(mutationCache, options)\n }\n\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(() => {\n const nextResult = replaceEqualDeep(\n resultRef.current,\n getResult(mutationCache, optionsRef.current),\n )\n if (resultRef.current !== nextResult) {\n resultRef.current = nextResult\n notifyManager.schedule(onStoreChange)\n }\n }),\n [mutationCache],\n ),\n () => resultRef.current,\n () => resultRef.current,\n )!\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAAS,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;;AA6BA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgB,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,aAAa,MAAM,OAAO,OAAO;CACvC,MAAM,YAAY,MAAM,OAAuB,IAAI;CACnD,IAAI,UAAU,YAAY,MACxB,UAAU,UAAU,UAAU,eAAe,OAAO;CAGtD,MAAM,gBAAgB;EACpB,WAAW,UAAU;CACvB,CAAC;CAED,OAAO,MAAM,qBACX,MAAM,aACH,kBACC,cAAc,gBAAgB;EAC5B,MAAM,aAAa,iBACjB,UAAU,SACV,UAAU,eAAe,WAAW,OAAO,CAC7C;EACA,IAAI,UAAU,YAAY,YAAY;GACpC,UAAU,UAAU;GACpB,cAAc,SAAS,aAAa;EACtC;CACF,CAAC,GACH,CAAC,aAAa,CAChB,SACM,UAAU,eACV,UAAU,OAClB;AACF"}
1
+ {"version":3,"file":"useMutationState.js","names":[],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Creates snapshot getters that share equal selected results across renders.\n * A new getter is created on each render. Each getter caches its snapshot until the matching mutations\n * or their states change.\n * @returns A factory for snapshot getters with a shared result cache.\n */\nfunction createSnapshotFactory<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>() {\n let previousResult: Array<TResult> | undefined\n\n return (\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n ) => {\n let inputs: Array<unknown> = []\n let snapshot: Array<TResult> | undefined\n\n return (): Array<TResult> => {\n const mutations = mutationCache.findAll(options.filters)\n const nextInputs = mutations.flatMap((mutation) => [\n mutation,\n mutation.state,\n ])\n\n if (\n !snapshot ||\n nextInputs.length !== inputs.length ||\n nextInputs.some((input, index) => !Object.is(input, inputs[index]))\n ) {\n inputs = nextInputs\n snapshot = replaceEqualDeep(\n previousResult,\n mutations.map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n ),\n )\n previousResult = snapshot\n }\n\n return snapshot\n }\n }\n}\n\n/**\n * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const [createSnapshot] = React.useState(() =>\n createSnapshotFactory<TResult, TMutation>(),\n )\n const getSnapshot = createSnapshot(mutationCache, options)\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)),\n [mutationCache],\n ),\n getSnapshot,\n getSnapshot,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAAS,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;AA4BA,SAAS,wBAIL;CACF,IAAI;CAEJ,QACE,eACA,YACG;EACH,IAAI,SAAyB,CAAC;EAC9B,IAAI;EAEJ,aAA6B;GAC3B,MAAM,YAAY,cAAc,QAAQ,QAAQ,OAAO;GACvD,MAAM,aAAa,UAAU,SAAS,aAAa,CACjD,UACA,SAAS,KACX,CAAC;GAED,IACE,CAAC,YACD,WAAW,WAAW,OAAO,UAC7B,WAAW,MAAM,OAAO,UAAU,CAAC,OAAO,GAAG,OAAO,OAAO,MAAM,CAAC,GAClE;IACA,SAAS;IACT,WAAW,iBACT,gBACA,UAAU,KACP,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB,CACF;IACA,iBAAiB;GACnB;GAEA,OAAO;EACT;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgB,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,CAAC,kBAAkB,MAAM,eAC7B,sBAA0C,CAC5C;CACA,MAAM,cAAc,eAAe,eAAe,OAAO;CAEzD,OAAO,MAAM,qBACX,MAAM,aACH,kBACC,cAAc,UAAU,cAAc,WAAW,aAAa,CAAC,GACjE,CAAC,aAAa,CAChB,GACA,aACA,WACF;AACF"}
@@ -14,7 +14,7 @@ let _tanstack_query_core = require("@tanstack/query-core");
14
14
  * @param query - The query, used to evaluate a `throwOnError` function against its error.
15
15
  */
16
16
  const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
17
- const throwOnError = query?.state.error && typeof options.throwOnError === "function" ? (0, _tanstack_query_core.shouldThrowError)(options.throwOnError, [query.state.error, query]) : options.throwOnError;
17
+ const throwOnError = query?.state.status === "error" && typeof options.throwOnError === "function" ? (0, _tanstack_query_core.shouldThrowError)(options.throwOnError, [query.state.error, query]) : options.throwOnError;
18
18
  if (options.suspense || throwOnError) {
19
19
  if (!errorResetBoundary.isReset()) options.retryOnMount = false;
20
20
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.cjs","names":["shouldThrowError"],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.error && typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [query.state.error, query])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,eACJ,OAAO,MAAM,SAAS,OAAO,QAAQ,iBAAiB,cAAA,GAClDA,qBAAAA,iBAAAA,CAAiB,QAAQ,cAAc,CAAC,MAAM,MAAM,OAAO,KAAK,CAAC,IACjE,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,MAAA,GAC5BA,qBAAAA,iBAAAA,CAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
1
+ {"version":3,"file":"errorBoundaryUtils.cjs","names":["shouldThrowError"],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.status === 'error' &&\n typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [\n query.state.error as TError,\n query,\n ])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,eACJ,OAAO,MAAM,WAAW,WACxB,OAAO,QAAQ,iBAAiB,cAAA,GAC5BA,qBAAAA,iBAAAA,CAAiB,QAAQ,cAAc,CACrC,MAAM,MAAM,OACZ,KACF,CAAC,IACD,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,MAAA,GAC5BA,qBAAAA,iBAAAA,CAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.d.cts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAoBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
1
+ {"version":3,"file":"errorBoundaryUtils.d.cts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAwBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.d.ts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAoBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
1
+ {"version":3,"file":"errorBoundaryUtils.d.ts","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"mappings":";;;;;;;;;;;qBAoBa,kCACX,cACA,QACA,OACA,YACA,kBAAkB,UAElB,SAAS,8BACP,cACA,QACA,OACA,YACA,YAEF,oBAAoB,8BACpB,OAAO,MAAM,cAAc,QAAQ,YAAY;;;;;;qBAwBpC,6BACX,oBAAoB;;;;;;;;;qBAeT,cACX,OACA,QACA,cACA,YACA,kBAAkB,YAClB,QAAA,oBAAA,cAAA,OAAA;EAOA,QAAQ,oBAAoB,OAAO;EACnC,oBAAoB;EACpB,cAAc,aAAa,cAAc,QAAQ,YAAY;EAC7D,OAAO,MAAM,cAAc,QAAQ,YAAY;EAC/C"}
@@ -11,7 +11,7 @@ import { shouldThrowError } from "@tanstack/query-core";
11
11
  * @param query - The query, used to evaluate a `throwOnError` function against its error.
12
12
  */
13
13
  const ensurePreventErrorBoundaryRetry = (options, errorResetBoundary, query) => {
14
- const throwOnError = query?.state.error && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
14
+ const throwOnError = query?.state.status === "error" && typeof options.throwOnError === "function" ? shouldThrowError(options.throwOnError, [query.state.error, query]) : options.throwOnError;
15
15
  if (options.suspense || throwOnError) {
16
16
  if (!errorResetBoundary.isReset()) options.retryOnMount = false;
17
17
  }
@@ -1 +1 @@
1
- {"version":3,"file":"errorBoundaryUtils.js","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.error && typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [query.state.error, query])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,eACJ,OAAO,MAAM,SAAS,OAAO,QAAQ,iBAAiB,aAClD,iBAAiB,QAAQ,cAAc,CAAC,MAAM,MAAM,OAAO,KAAK,CAAC,IACjE,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,KAC5B,iBAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
1
+ {"version":3,"file":"errorBoundaryUtils.js","names":[],"sources":["../../src/errorBoundaryUtils.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\nimport { shouldThrowError } from '@tanstack/query-core'\nimport type {\n DefaultedQueryObserverOptions,\n Query,\n QueryKey,\n QueryObserverResult,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'\n\n/**\n * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`),\n * unless the error boundary has been reset, so a remount doesn't retry the failed query before the\n * user resets the boundary. Mutates the options.\n * @param options - The defaulted query options to adjust.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n * @param query - The query, used to evaluate a `throwOnError` function against its error.\n */\nexport const ensurePreventErrorBoundaryRetry = <\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey extends QueryKey,\n>(\n options: DefaultedQueryObserverOptions<\n TQueryFnData,\n TError,\n TData,\n TQueryData,\n TQueryKey\n >,\n errorResetBoundary: QueryErrorResetBoundaryValue,\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,\n) => {\n const throwOnError =\n query?.state.status === 'error' &&\n typeof options.throwOnError === 'function'\n ? shouldThrowError(options.throwOnError, [\n query.state.error as TError,\n query,\n ])\n : options.throwOnError\n\n if (options.suspense || throwOnError) {\n // Prevent retrying failed query if the error boundary has not been reset yet\n if (!errorResetBoundary.isReset()) {\n options.retryOnMount = false\n }\n }\n}\n\n/**\n * Clears the reset state of the error boundary after the component mounts, so later errors are\n * thrown to the boundary again.\n * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`.\n */\nexport const useClearResetErrorBoundary = (\n errorResetBoundary: QueryErrorResetBoundaryValue,\n) => {\n React.useEffect(() => {\n errorResetBoundary.clearReset()\n }, [errorResetBoundary])\n}\n\n/**\n * Checks whether the query error should be thrown to the nearest error boundary: the query errored\n * and isn't fetching, the boundary hasn't been reset, and either `suspense` is enabled with no data\n * or `throwOnError` says so.\n * @param params - The observer `result`, the `errorResetBoundary`, the `throwOnError` option, the\n * `query`, and the `suspense` option.\n * @returns `true` if the error should be thrown.\n */\nexport const getHasError = <\n TData,\n TError,\n TQueryFnData,\n TQueryData,\n TQueryKey extends QueryKey,\n>({\n result,\n errorResetBoundary,\n throwOnError,\n query,\n suspense,\n}: {\n result: QueryObserverResult<TData, TError>\n errorResetBoundary: QueryErrorResetBoundaryValue\n throwOnError: ThrowOnError<TQueryFnData, TError, TQueryData, TQueryKey>\n query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined\n suspense: boolean | undefined\n}) => {\n return (\n result.isError &&\n !errorResetBoundary.isReset() &&\n !result.isFetching &&\n query &&\n ((suspense && result.data === undefined) ||\n shouldThrowError(throwOnError, [result.error, query]))\n )\n}\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAa,mCAOX,SAOA,oBACA,UACG;CACH,MAAM,eACJ,OAAO,MAAM,WAAW,WACxB,OAAO,QAAQ,iBAAiB,aAC5B,iBAAiB,QAAQ,cAAc,CACrC,MAAM,MAAM,OACZ,KACF,CAAC,IACD,QAAQ;CAEd,IAAI,QAAQ,YAAY,cAElB;MAAA,CAAC,mBAAmB,QAAQ,GAC9B,QAAQ,eAAe;CAAA;AAG7B;;;;;;AAOA,MAAa,8BACX,uBACG;CACH,MAAM,gBAAgB;EACpB,mBAAmB,WAAW;CAChC,GAAG,CAAC,kBAAkB,CAAC;AACzB;;;;;;;;;AAUA,MAAa,eAMX,EACA,QACA,oBACA,cACA,OACA,eAOI;CACJ,OACE,OAAO,WACP,CAAC,mBAAmB,QAAQ,KAC5B,CAAC,OAAO,cACR,UACE,YAAY,OAAO,SAAS,KAAA,KAC5B,iBAAiB,cAAc,CAAC,OAAO,OAAO,KAAK,CAAC;AAE1D"}
@@ -33,14 +33,27 @@ function useIsMutating(filters, queryClient) {
33
33
  } }, client).length;
34
34
  }
35
35
  /**
36
- * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
37
- * (or to their state, by default).
38
- * @param mutationCache - The mutation cache to read.
39
- * @param options - The `filters` to match and the `select` function to map each mutation with.
40
- * @returns The selected value of every matching mutation.
36
+ * Creates snapshot getters that share equal selected results across renders.
37
+ * A new getter is created on each render. Each getter caches its snapshot until the matching mutations
38
+ * or their states change.
39
+ * @returns A factory for snapshot getters with a shared result cache.
41
40
  */
42
- function getResult(mutationCache, options) {
43
- return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
41
+ function createSnapshotFactory() {
42
+ let previousResult;
43
+ return (mutationCache, options) => {
44
+ let inputs = [];
45
+ let snapshot;
46
+ return () => {
47
+ const mutations = mutationCache.findAll(options.filters);
48
+ const nextInputs = mutations.flatMap((mutation) => [mutation, mutation.state]);
49
+ if (!snapshot || nextInputs.length !== inputs.length || nextInputs.some((input, index) => !Object.is(input, inputs[index]))) {
50
+ inputs = nextInputs;
51
+ snapshot = (0, _tanstack_query_core.replaceEqualDeep)(previousResult, mutations.map((mutation) => options.select ? options.select(mutation) : mutation.state));
52
+ previousResult = snapshot;
53
+ }
54
+ return snapshot;
55
+ };
56
+ };
44
57
  }
45
58
  /**
46
59
  * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
@@ -113,19 +126,9 @@ function getResult(mutationCache, options) {
113
126
  */
114
127
  function useMutationState(options = {}, queryClient) {
115
128
  const mutationCache = require_QueryClientProvider.useQueryClient(queryClient).getMutationCache();
116
- const optionsRef = react.useRef(options);
117
- const resultRef = react.useRef(null);
118
- if (resultRef.current === null) resultRef.current = getResult(mutationCache, options);
119
- react.useEffect(() => {
120
- optionsRef.current = options;
121
- });
122
- return react.useSyncExternalStore(react.useCallback((onStoreChange) => mutationCache.subscribe(() => {
123
- const nextResult = (0, _tanstack_query_core.replaceEqualDeep)(resultRef.current, getResult(mutationCache, optionsRef.current));
124
- if (resultRef.current !== nextResult) {
125
- resultRef.current = nextResult;
126
- _tanstack_query_core.notifyManager.schedule(onStoreChange);
127
- }
128
- }), [mutationCache]), () => resultRef.current, () => resultRef.current);
129
+ const [createSnapshot] = react.useState(() => createSnapshotFactory());
130
+ const getSnapshot = createSnapshot(mutationCache, options);
131
+ return react.useSyncExternalStore(react.useCallback((onStoreChange) => mutationCache.subscribe(_tanstack_query_core.notifyManager.batchCalls(onStoreChange)), [mutationCache]), getSnapshot, getSnapshot);
129
132
  }
130
133
  //#endregion
131
134
  exports.useIsMutating = useIsMutating;
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","React","replaceEqualDeep"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`\n * (or to their state, by default).\n * @param mutationCache - The mutation cache to read.\n * @param options - The `filters` to match and the `select` function to map each mutation with.\n * @returns The selected value of every matching mutation.\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 * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const optionsRef = React.useRef(options)\n const resultRef = React.useRef<Array<TResult>>(null)\n if (resultRef.current === null) {\n resultRef.current = getResult(mutationCache, options)\n }\n\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(() => {\n const nextResult = replaceEqualDeep(\n resultRef.current,\n getResult(mutationCache, optionsRef.current),\n )\n if (resultRef.current !== nextResult) {\n resultRef.current = nextResult\n notifyManager.schedule(onStoreChange)\n }\n }),\n [mutationCache],\n ),\n () => resultRef.current,\n () => resultRef.current,\n )!\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;;AA6BA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBA,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,aAAaC,MAAM,OAAO,OAAO;CACvC,MAAM,YAAYA,MAAM,OAAuB,IAAI;CACnD,IAAI,UAAU,YAAY,MACxB,UAAU,UAAU,UAAU,eAAe,OAAO;CAGtD,MAAM,gBAAgB;EACpB,WAAW,UAAU;CACvB,CAAC;CAED,OAAOA,MAAM,qBACXA,MAAM,aACH,kBACC,cAAc,gBAAgB;EAC5B,MAAM,cAAA,GAAaC,qBAAAA,iBAAAA,CACjB,UAAU,SACV,UAAU,eAAe,WAAW,OAAO,CAC7C;EACA,IAAI,UAAU,YAAY,YAAY;GACpC,UAAU,UAAU;GACpB,qBAAA,cAAc,SAAS,aAAa;EACtC;CACF,CAAC,GACH,CAAC,aAAa,CAChB,SACM,UAAU,eACV,UAAU,OAClB;AACF"}
1
+ {"version":3,"file":"useMutationState.cjs","names":["useQueryClient","replaceEqualDeep","React","notifyManager"],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Creates snapshot getters that share equal selected results across renders.\n * A new getter is created on each render. Each getter caches its snapshot until the matching mutations\n * or their states change.\n * @returns A factory for snapshot getters with a shared result cache.\n */\nfunction createSnapshotFactory<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>() {\n let previousResult: Array<TResult> | undefined\n\n return (\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n ) => {\n let inputs: Array<unknown> = []\n let snapshot: Array<TResult> | undefined\n\n return (): Array<TResult> => {\n const mutations = mutationCache.findAll(options.filters)\n const nextInputs = mutations.flatMap((mutation) => [\n mutation,\n mutation.state,\n ])\n\n if (\n !snapshot ||\n nextInputs.length !== inputs.length ||\n nextInputs.some((input, index) => !Object.is(input, inputs[index]))\n ) {\n inputs = nextInputs\n snapshot = replaceEqualDeep(\n previousResult,\n mutations.map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n ),\n )\n previousResult = snapshot\n }\n\n return snapshot\n }\n }\n}\n\n/**\n * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const [createSnapshot] = React.useState(() =>\n createSnapshotFactory<TResult, TMutation>(),\n )\n const getSnapshot = createSnapshot(mutationCache, options)\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)),\n [mutationCache],\n ),\n getSnapshot,\n getSnapshot,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;AA4BA,SAAS,wBAIL;CACF,IAAI;CAEJ,QACE,eACA,YACG;EACH,IAAI,SAAyB,CAAC;EAC9B,IAAI;EAEJ,aAA6B;GAC3B,MAAM,YAAY,cAAc,QAAQ,QAAQ,OAAO;GACvD,MAAM,aAAa,UAAU,SAAS,aAAa,CACjD,UACA,SAAS,KACX,CAAC;GAED,IACE,CAAC,YACD,WAAW,WAAW,OAAO,UAC7B,WAAW,MAAM,OAAO,UAAU,CAAC,OAAO,GAAG,OAAO,OAAO,MAAM,CAAC,GAClE;IACA,SAAS;IACT,YAAA,GAAWC,qBAAAA,iBAAAA,CACT,gBACA,UAAU,KACP,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB,CACF;IACA,iBAAiB;GACnB;GAEA,OAAO;EACT;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgBD,4BAAAA,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,CAAC,kBAAkBE,MAAM,eAC7B,sBAA0C,CAC5C;CACA,MAAM,cAAc,eAAe,eAAe,OAAO;CAEzD,OAAOA,MAAM,qBACXA,MAAM,aACH,kBACC,cAAc,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,GACjE,CAAC,aAAa,CAChB,GACA,aACA,WACF;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.d.cts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiGpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
1
+ {"version":3,"file":"useMutationState.d.cts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0HpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.d.ts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAiGpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
1
+ {"version":3,"file":"useMutationState.d.ts","names":[],"sources":["../../src/useMutationState.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;wBAgCgB,cACd,UAAU,iBACV,cAAc;KASX,uBAAuB,YAAY,kBACtC,oBACQ,aACA,cACA,kBACA,oBAGN,SAAS,OAAO,QAAQ,YAAY,mBACpC;KAEC,qBACH,UAAU,eACV,kBAAkB,+BAChB,uBAAuB;EAEzB,UAAU;EACV,UAAU,UAAU,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0HpB,iBACd,UAAU,eACV,kBAAkB,+BAChB,uBAAuB,UAEzB,UAAS,qBAAqB,SAAS,YACvC,cAAc,cACb,MAAM"}
@@ -30,14 +30,27 @@ function useIsMutating(filters, queryClient) {
30
30
  } }, client).length;
31
31
  }
32
32
  /**
33
- * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
34
- * (or to their state, by default).
35
- * @param mutationCache - The mutation cache to read.
36
- * @param options - The `filters` to match and the `select` function to map each mutation with.
37
- * @returns The selected value of every matching mutation.
33
+ * Creates snapshot getters that share equal selected results across renders.
34
+ * A new getter is created on each render. Each getter caches its snapshot until the matching mutations
35
+ * or their states change.
36
+ * @returns A factory for snapshot getters with a shared result cache.
38
37
  */
39
- function getResult(mutationCache, options) {
40
- return mutationCache.findAll(options.filters).map((mutation) => options.select ? options.select(mutation) : mutation.state);
38
+ function createSnapshotFactory() {
39
+ let previousResult;
40
+ return (mutationCache, options) => {
41
+ let inputs = [];
42
+ let snapshot;
43
+ return () => {
44
+ const mutations = mutationCache.findAll(options.filters);
45
+ const nextInputs = mutations.flatMap((mutation) => [mutation, mutation.state]);
46
+ if (!snapshot || nextInputs.length !== inputs.length || nextInputs.some((input, index) => !Object.is(input, inputs[index]))) {
47
+ inputs = nextInputs;
48
+ snapshot = replaceEqualDeep(previousResult, mutations.map((mutation) => options.select ? options.select(mutation) : mutation.state));
49
+ previousResult = snapshot;
50
+ }
51
+ return snapshot;
52
+ };
53
+ };
41
54
  }
42
55
  /**
43
56
  * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
@@ -110,19 +123,9 @@ function getResult(mutationCache, options) {
110
123
  */
111
124
  function useMutationState(options = {}, queryClient) {
112
125
  const mutationCache = useQueryClient(queryClient).getMutationCache();
113
- const optionsRef = React.useRef(options);
114
- const resultRef = React.useRef(null);
115
- if (resultRef.current === null) resultRef.current = getResult(mutationCache, options);
116
- React.useEffect(() => {
117
- optionsRef.current = options;
118
- });
119
- return React.useSyncExternalStore(React.useCallback((onStoreChange) => mutationCache.subscribe(() => {
120
- const nextResult = replaceEqualDeep(resultRef.current, getResult(mutationCache, optionsRef.current));
121
- if (resultRef.current !== nextResult) {
122
- resultRef.current = nextResult;
123
- notifyManager.schedule(onStoreChange);
124
- }
125
- }), [mutationCache]), () => resultRef.current, () => resultRef.current);
126
+ const [createSnapshot] = React.useState(() => createSnapshotFactory());
127
+ const getSnapshot = createSnapshot(mutationCache, options);
128
+ return React.useSyncExternalStore(React.useCallback((onStoreChange) => mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), [mutationCache]), getSnapshot, getSnapshot);
126
129
  }
127
130
  //#endregion
128
131
  export { useIsMutating, useMutationState };
@@ -1 +1 @@
1
- {"version":3,"file":"useMutationState.js","names":[],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`\n * (or to their state, by default).\n * @param mutationCache - The mutation cache to read.\n * @param options - The `filters` to match and the `select` function to map each mutation with.\n * @returns The selected value of every matching mutation.\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 * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const optionsRef = React.useRef(options)\n const resultRef = React.useRef<Array<TResult>>(null)\n if (resultRef.current === null) {\n resultRef.current = getResult(mutationCache, options)\n }\n\n React.useEffect(() => {\n optionsRef.current = options\n })\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(() => {\n const nextResult = replaceEqualDeep(\n resultRef.current,\n getResult(mutationCache, optionsRef.current),\n )\n if (resultRef.current !== nextResult) {\n resultRef.current = nextResult\n notifyManager.schedule(onStoreChange)\n }\n }),\n [mutationCache],\n ),\n () => resultRef.current,\n () => resultRef.current,\n )!\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAAS,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;;AA6BA,SAAS,UAKP,eACA,SACgB;CAChB,OAAO,cACJ,QAAQ,QAAQ,OAAO,CAAC,CACxB,KACE,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB;AACJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgB,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,aAAa,MAAM,OAAO,OAAO;CACvC,MAAM,YAAY,MAAM,OAAuB,IAAI;CACnD,IAAI,UAAU,YAAY,MACxB,UAAU,UAAU,UAAU,eAAe,OAAO;CAGtD,MAAM,gBAAgB;EACpB,WAAW,UAAU;CACvB,CAAC;CAED,OAAO,MAAM,qBACX,MAAM,aACH,kBACC,cAAc,gBAAgB;EAC5B,MAAM,aAAa,iBACjB,UAAU,SACV,UAAU,eAAe,WAAW,OAAO,CAC7C;EACA,IAAI,UAAU,YAAY,YAAY;GACpC,UAAU,UAAU;GACpB,cAAc,SAAS,aAAa;EACtC;CACF,CAAC,GACH,CAAC,aAAa,CAChB,SACM,UAAU,eACV,UAAU,OAClB;AACF"}
1
+ {"version":3,"file":"useMutationState.js","names":[],"sources":["../../src/useMutationState.ts"],"sourcesContent":["'use client'\nimport * as React from 'react'\n\nimport { notifyManager, replaceEqualDeep } from '@tanstack/query-core'\nimport { useQueryClient } from './QueryClientProvider'\nimport type {\n Mutation,\n MutationCache,\n MutationFilters,\n MutationState,\n QueryClient,\n} from '@tanstack/query-core'\n\n/**\n * The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`\n * (useful for app-wide loading indicators).\n * @param filters - The {@link MutationFilters} to narrow down the matched mutations.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be the `number` of the mutations that your application currently has `pending`.\n * @example\n * ```tsx\n * import { useIsMutating } from '@tanstack/react-query'\n *\n * function PostsMutatingIndicator() {\n * // How many mutations matching the posts prefix are in progress?\n * const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })\n *\n * return isMutatingPosts ? <span>Saving posts...</span> : null\n * }\n * ```\n */\nexport function useIsMutating(\n filters?: MutationFilters,\n queryClient?: QueryClient,\n): number {\n const client = useQueryClient(queryClient)\n return useMutationState(\n { filters: { ...filters, status: 'pending' } },\n client,\n ).length\n}\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\ntype MutationStateOptions<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n> = {\n filters?: MutationFilters\n select?: (mutation: TMutation) => TResult\n}\n\n/**\n * Creates snapshot getters that share equal selected results across renders.\n * A new getter is created on each render. Each getter caches its snapshot until the matching mutations\n * or their states change.\n * @returns A factory for snapshot getters with a shared result cache.\n */\nfunction createSnapshotFactory<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>() {\n let previousResult: Array<TResult> | undefined\n\n return (\n mutationCache: MutationCache,\n options: MutationStateOptions<TResult, TMutation>,\n ) => {\n let inputs: Array<unknown> = []\n let snapshot: Array<TResult> | undefined\n\n return (): Array<TResult> => {\n const mutations = mutationCache.findAll(options.filters)\n const nextInputs = mutations.flatMap((mutation) => [\n mutation,\n mutation.state,\n ])\n\n if (\n !snapshot ||\n nextInputs.length !== inputs.length ||\n nextInputs.some((input, index) => !Object.is(input, inputs[index]))\n ) {\n inputs = nextInputs\n snapshot = replaceEqualDeep(\n previousResult,\n mutations.map(\n (mutation): TResult =>\n (options.select\n ? options.select(mutation as TMutation)\n : mutation.state) as TResult,\n ),\n )\n previousResult = snapshot\n }\n\n return snapshot\n }\n }\n}\n\n/**\n * `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass\n * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation\n * state.\n * @param options - The `filters` to narrow down matched mutations, and an optional `select` to transform the\n * mutation state.\n * @param queryClient - Use this to use a custom `QueryClient`. Otherwise, the one from the nearest context will\n * be used.\n * @returns Will be an Array of whatever `select` returns for each matching mutation.\n * @example\n * Get all variables of all running mutations:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function PendingPosts() {\n * const pendingVariables = useMutationState({\n * filters: { status: 'pending' },\n * select: (mutation) => mutation.state.variables,\n * })\n *\n * return <>{pendingVariables.length} posts saving...</>\n * }\n * ```\n * @example\n * Get all data for specific mutations via the `mutationKey`:\n * ```tsx\n * import { useMutation, useMutationState } from '@tanstack/react-query'\n *\n * const mutationKey = ['posts']\n *\n * function Posts() {\n * // Some mutation that we want to get the state for\n * const mutation = useMutation({\n * mutationKey,\n * mutationFn: createPosts,\n * })\n *\n * const savedPosts = useMutationState({\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 * return (\n * <button onClick={() => mutation.mutate(['New Post'])}>\n * Create post ({savedPosts.length} saved so far)\n * </button>\n * )\n * }\n * ```\n * @example\n * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new\n * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the\n * last item that `useMutationState` returns to get the latest successful invocation:\n * ```tsx\n * import { useMutationState } from '@tanstack/react-query'\n *\n * function LatestPost() {\n * const savedPosts = useMutationState({\n * filters: { mutationKey: ['posts'], status: 'success' },\n * select: (mutation) => mutation.state.data,\n * })\n *\n * const latestSavedPost = savedPosts[savedPosts.length - 1]\n *\n * return <>{latestSavedPost ? 'Saved' : 'Nothing saved yet'}</>\n * }\n * ```\n */\nexport function useMutationState<\n TResult = MutationState,\n TMutation extends Mutation<any, any, any, any> =\n MutationTypeFromResult<TResult>,\n>(\n options: MutationStateOptions<TResult, TMutation> = {},\n queryClient?: QueryClient,\n): Array<TResult> {\n const mutationCache = useQueryClient(queryClient).getMutationCache()\n const [createSnapshot] = React.useState(() =>\n createSnapshotFactory<TResult, TMutation>(),\n )\n const getSnapshot = createSnapshot(mutationCache, options)\n\n return React.useSyncExternalStore(\n React.useCallback(\n (onStoreChange) =>\n mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)),\n [mutationCache],\n ),\n getSnapshot,\n getSnapshot,\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,cACd,SACA,aACQ;CACR,MAAM,SAAS,eAAe,WAAW;CACzC,OAAO,iBACL,EAAE,SAAS;EAAE,GAAG;EAAS,QAAQ;CAAU,EAAE,GAC7C,MACF,CAAC,CAAC;AACJ;;;;;;;AA4BA,SAAS,wBAIL;CACF,IAAI;CAEJ,QACE,eACA,YACG;EACH,IAAI,SAAyB,CAAC;EAC9B,IAAI;EAEJ,aAA6B;GAC3B,MAAM,YAAY,cAAc,QAAQ,QAAQ,OAAO;GACvD,MAAM,aAAa,UAAU,SAAS,aAAa,CACjD,UACA,SAAS,KACX,CAAC;GAED,IACE,CAAC,YACD,WAAW,WAAW,OAAO,UAC7B,WAAW,MAAM,OAAO,UAAU,CAAC,OAAO,GAAG,OAAO,OAAO,MAAM,CAAC,GAClE;IACA,SAAS;IACT,WAAW,iBACT,gBACA,UAAU,KACP,aACE,QAAQ,SACL,QAAQ,OAAO,QAAqB,IACpC,SAAS,KACjB,CACF;IACA,iBAAiB;GACnB;GAEA,OAAO;EACT;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,SAAgB,iBAKd,UAAoD,CAAC,GACrD,aACgB;CAChB,MAAM,gBAAgB,eAAe,WAAW,CAAC,CAAC,iBAAiB;CACnE,MAAM,CAAC,kBAAkB,MAAM,eAC7B,sBAA0C,CAC5C;CACA,MAAM,cAAc,eAAe,eAAe,OAAO;CAEzD,OAAO,MAAM,qBACX,MAAM,aACH,kBACC,cAAc,UAAU,cAAc,WAAW,aAAa,CAAC,GACjE,CAAC,aAAa,CAChB,GACA,aACA,WACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/react-query",
3
- "version": "5.104.3",
3
+ "version": "5.104.5",
4
4
  "description": "Hooks for managing, caching and syncing asynchronous and remote data in React",
5
5
  "author": "tannerlinsley",
6
6
  "license": "MIT",
@@ -44,11 +44,11 @@
44
44
  "!build/codemods/**/__tests__"
45
45
  ],
46
46
  "dependencies": {
47
- "@tanstack/query-core": "5.104.3"
47
+ "@tanstack/query-core": "5.104.5"
48
48
  },
49
49
  "devDependencies": {
50
50
  "@eslint-react/eslint-plugin": "^5.23.3",
51
- "@tanstack/query-persist-client-core": "5.104.3",
51
+ "@tanstack/query-persist-client-core": "5.104.5",
52
52
  "@tanstack/query-test-utils": "0.0.0",
53
53
  "@testing-library/react": "^16.1.0",
54
54
  "@testing-library/react-render-stream": "^2.0.2",
@@ -62,8 +62,14 @@
62
62
  "typescript": "6.0.3"
63
63
  },
64
64
  "peerDependencies": {
65
+ "@types/react": "^18 || ^19",
65
66
  "react": "^18 || ^19"
66
67
  },
68
+ "peerDependenciesMeta": {
69
+ "@types/react": {
70
+ "optional": true
71
+ }
72
+ },
67
73
  "scripts": {
68
74
  "clean": "premove ./build ./coverage ./dist-ts ./.cache/test-types",
69
75
  "compile": "tsc --project tsconfig.json",
@@ -36,8 +36,12 @@ export const ensurePreventErrorBoundaryRetry = <
36
36
  query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,
37
37
  ) => {
38
38
  const throwOnError =
39
- query?.state.error && typeof options.throwOnError === 'function'
40
- ? shouldThrowError(options.throwOnError, [query.state.error, query])
39
+ query?.state.status === 'error' &&
40
+ typeof options.throwOnError === 'function'
41
+ ? shouldThrowError(options.throwOnError, [
42
+ query.state.error as TError,
43
+ query,
44
+ ])
41
45
  : options.throwOnError
42
46
 
43
47
  if (options.suspense || throwOnError) {
@@ -62,28 +62,53 @@ type MutationStateOptions<
62
62
  }
63
63
 
64
64
  /**
65
- * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
66
- * (or to their state, by default).
67
- * @param mutationCache - The mutation cache to read.
68
- * @param options - The `filters` to match and the `select` function to map each mutation with.
69
- * @returns The selected value of every matching mutation.
65
+ * Creates snapshot getters that share equal selected results across renders.
66
+ * A new getter is created on each render. Each getter caches its snapshot until the matching mutations
67
+ * or their states change.
68
+ * @returns A factory for snapshot getters with a shared result cache.
70
69
  */
71
- function getResult<
70
+ function createSnapshotFactory<
72
71
  TResult = MutationState,
73
72
  TMutation extends Mutation<any, any, any, any> =
74
73
  MutationTypeFromResult<TResult>,
75
- >(
76
- mutationCache: MutationCache,
77
- options: MutationStateOptions<TResult, TMutation>,
78
- ): Array<TResult> {
79
- return mutationCache
80
- .findAll(options.filters)
81
- .map(
82
- (mutation): TResult =>
83
- (options.select
84
- ? options.select(mutation as TMutation)
85
- : mutation.state) as TResult,
86
- )
74
+ >() {
75
+ let previousResult: Array<TResult> | undefined
76
+
77
+ return (
78
+ mutationCache: MutationCache,
79
+ options: MutationStateOptions<TResult, TMutation>,
80
+ ) => {
81
+ let inputs: Array<unknown> = []
82
+ let snapshot: Array<TResult> | undefined
83
+
84
+ return (): Array<TResult> => {
85
+ const mutations = mutationCache.findAll(options.filters)
86
+ const nextInputs = mutations.flatMap((mutation) => [
87
+ mutation,
88
+ mutation.state,
89
+ ])
90
+
91
+ if (
92
+ !snapshot ||
93
+ nextInputs.length !== inputs.length ||
94
+ nextInputs.some((input, index) => !Object.is(input, inputs[index]))
95
+ ) {
96
+ inputs = nextInputs
97
+ snapshot = replaceEqualDeep(
98
+ previousResult,
99
+ mutations.map(
100
+ (mutation): TResult =>
101
+ (options.select
102
+ ? options.select(mutation as TMutation)
103
+ : mutation.state) as TResult,
104
+ ),
105
+ )
106
+ previousResult = snapshot
107
+ }
108
+
109
+ return snapshot
110
+ }
111
+ }
87
112
  }
88
113
 
89
114
  /**
@@ -164,32 +189,18 @@ export function useMutationState<
164
189
  queryClient?: QueryClient,
165
190
  ): Array<TResult> {
166
191
  const mutationCache = useQueryClient(queryClient).getMutationCache()
167
- const optionsRef = React.useRef(options)
168
- const resultRef = React.useRef<Array<TResult>>(null)
169
- if (resultRef.current === null) {
170
- resultRef.current = getResult(mutationCache, options)
171
- }
172
-
173
- React.useEffect(() => {
174
- optionsRef.current = options
175
- })
192
+ const [createSnapshot] = React.useState(() =>
193
+ createSnapshotFactory<TResult, TMutation>(),
194
+ )
195
+ const getSnapshot = createSnapshot(mutationCache, options)
176
196
 
177
197
  return React.useSyncExternalStore(
178
198
  React.useCallback(
179
199
  (onStoreChange) =>
180
- mutationCache.subscribe(() => {
181
- const nextResult = replaceEqualDeep(
182
- resultRef.current,
183
- getResult(mutationCache, optionsRef.current),
184
- )
185
- if (resultRef.current !== nextResult) {
186
- resultRef.current = nextResult
187
- notifyManager.schedule(onStoreChange)
188
- }
189
- }),
200
+ mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)),
190
201
  [mutationCache],
191
202
  ),
192
- () => resultRef.current,
193
- () => resultRef.current,
194
- )!
203
+ getSnapshot,
204
+ getSnapshot,
205
+ )
195
206
  }