@tanstack/preact-query 5.102.6 → 5.102.8

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.
@@ -62,14 +62,16 @@ function useQueries({ queries, ...options }, queryClient) {
62
62
  const client = require_QueryClientProvider.useQueryClient(queryClient);
63
63
  const isRestoring = require_IsRestoringProvider.useIsRestoring();
64
64
  const errorResetBoundary = require_QueryErrorResetBoundary.useQueryErrorResetBoundary();
65
+ const subscribed = options.subscribed !== false;
65
66
  const defaultedQueries = (0, preact_hooks.useMemo)(() => queries.map((opts) => {
66
67
  const defaultedOptions = client.defaultQueryOptions(opts);
67
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
68
+ defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : subscribed ? "optimistic" : void 0;
68
69
  return defaultedOptions;
69
70
  }), [
70
71
  queries,
71
72
  client,
72
- isRestoring
73
+ isRestoring,
74
+ subscribed
73
75
  ]);
74
76
  defaultedQueries.forEach((queryOptions) => {
75
77
  require_suspense.ensureSuspenseTimers(queryOptions);
@@ -79,7 +81,7 @@ function useQueries({ queries, ...options }, queryClient) {
79
81
  require_errorBoundaryUtils.useClearResetErrorBoundary(errorResetBoundary);
80
82
  const [observer] = (0, preact_hooks.useState)(() => new _tanstack_query_core.QueriesObserver(client, defaultedQueries, options));
81
83
  const [optimisticResult, getCombinedResult, trackResult] = observer.getOptimisticResult(defaultedQueries, options.combine);
82
- const shouldSubscribe = !isRestoring && options.subscribed !== false;
84
+ const shouldSubscribe = !isRestoring && subscribed;
83
85
  require_utils.useSyncExternalStore((0, preact_hooks.useCallback)((onStoreChange) => shouldSubscribe ? observer.subscribe(_tanstack_query_core.notifyManager.batchCalls(onStoreChange)) : _tanstack_query_core.noop, [observer, shouldSubscribe]), () => observer.getCurrentResult());
84
86
  (0, preact_hooks.useEffect)(() => {
85
87
  observer.setQueries(defaultedQueries, options);
@@ -107,7 +109,7 @@ function useQueries({ queries, ...options }, queryClient) {
107
109
  suspense: query.suspense
108
110
  });
109
111
  });
110
- if (firstSingleResultWhichShouldThrow === null || firstSingleResultWhichShouldThrow === void 0 ? void 0 : firstSingleResultWhichShouldThrow.error) throw firstSingleResultWhichShouldThrow.error;
112
+ if (firstSingleResultWhichShouldThrow) throw firstSingleResultWhichShouldThrow.error;
111
113
  return getCombinedResult(trackResult());
112
114
  }
113
115
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"useQueries.cjs","names":["useQueryClient","useIsRestoring","useQueryErrorResetBoundary","useMemo","useState","QueriesObserver","useCallback","notifyManager","noop","shouldSuspend","QueryObserver","fetchOptimistic","getHasError"],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions\n }),\n [queries, client, isRestoring],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && options.subscribed !== false\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow?.error) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,MAAM,cAAcC,4BAAAA,eAAe;CACnC,MAAM,qBAAqBC,gCAAAA,2BAA2B;CAEtD,MAAM,oBAAA,GAAmBC,aAAAA,QAAAA,OAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA;EAEJ,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;CAAW,CAC/B;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,iBAAA,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,2BAAA,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAAA,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,aAAA,GAAYC,aAAAA,SAAAA,OAEf,IAAIC,qBAAAA,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe,QAAQ,eAAe;CAC/D,cAAA,sBAAA,GACEC,aAAAA,YAAAA,EACG,kBACC,kBACI,SAAS,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,IAC1DC,qBAAAA,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7DC,iBAAAA,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQA,iBAAAA,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAIC,qBAAAA,cAAc,QAAQ,IAAI;GACpD,OAAOC,iBAAAA,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACAC,2BAAAA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAA,sCAAA,QAAA,sCAAA,KAAA,IAAA,KAAA,IAAI,kCAAmC,OACrC,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
1
+ {"version":3,"file":"useQueries.cjs","names":["useQueryClient","useIsRestoring","useQueryErrorResetBoundary","useMemo","useState","QueriesObserver","useCallback","notifyManager","noop","shouldSuspend","QueryObserver","fetchOptimistic","getHasError"],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n const subscribed = options.subscribed !== false\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : subscribed\n ? 'optimistic'\n : undefined\n\n return defaultedOptions\n }),\n [queries, client, isRestoring, subscribed],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && subscribed\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,MAAM,cAAcC,4BAAAA,eAAe;CACnC,MAAM,qBAAqBC,gCAAAA,2BAA2B;CACtD,MAAM,aAAa,QAAQ,eAAe;CAE1C,MAAM,oBAAA,GAAmBC,aAAAA,QAAAA,OAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA,aACE,eACA,KAAA;EAEN,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;EAAa;CAAU,CAC3C;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,iBAAA,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,2BAAA,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAAA,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,aAAA,GAAYC,aAAAA,SAAAA,OAEf,IAAIC,qBAAAA,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe;CACxC,cAAA,sBAAA,GACEC,aAAAA,YAAAA,EACG,kBACC,kBACI,SAAS,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,IAC1DC,qBAAAA,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7DC,iBAAAA,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQA,iBAAAA,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAIC,qBAAAA,cAAc,QAAQ,IAAI;GACpD,OAAOC,iBAAAA,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACAC,2BAAAA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAI,mCACF,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
@@ -61,14 +61,16 @@ function useQueries({ queries, ...options }, queryClient) {
61
61
  const client = useQueryClient(queryClient);
62
62
  const isRestoring = useIsRestoring();
63
63
  const errorResetBoundary = useQueryErrorResetBoundary();
64
+ const subscribed = options.subscribed !== false;
64
65
  const defaultedQueries = useMemo(() => queries.map((opts) => {
65
66
  const defaultedOptions = client.defaultQueryOptions(opts);
66
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
67
+ defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : subscribed ? "optimistic" : void 0;
67
68
  return defaultedOptions;
68
69
  }), [
69
70
  queries,
70
71
  client,
71
- isRestoring
72
+ isRestoring,
73
+ subscribed
72
74
  ]);
73
75
  defaultedQueries.forEach((queryOptions) => {
74
76
  ensureSuspenseTimers(queryOptions);
@@ -78,7 +80,7 @@ function useQueries({ queries, ...options }, queryClient) {
78
80
  useClearResetErrorBoundary(errorResetBoundary);
79
81
  const [observer] = useState(() => new QueriesObserver(client, defaultedQueries, options));
80
82
  const [optimisticResult, getCombinedResult, trackResult] = observer.getOptimisticResult(defaultedQueries, options.combine);
81
- const shouldSubscribe = !isRestoring && options.subscribed !== false;
83
+ const shouldSubscribe = !isRestoring && subscribed;
82
84
  useSyncExternalStore(useCallback((onStoreChange) => shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop, [observer, shouldSubscribe]), () => observer.getCurrentResult());
83
85
  useEffect(() => {
84
86
  observer.setQueries(defaultedQueries, options);
@@ -106,7 +108,7 @@ function useQueries({ queries, ...options }, queryClient) {
106
108
  suspense: query.suspense
107
109
  });
108
110
  });
109
- if (firstSingleResultWhichShouldThrow === null || firstSingleResultWhichShouldThrow === void 0 ? void 0 : firstSingleResultWhichShouldThrow.error) throw firstSingleResultWhichShouldThrow.error;
111
+ if (firstSingleResultWhichShouldThrow) throw firstSingleResultWhichShouldThrow.error;
110
112
  return getCombinedResult(trackResult());
111
113
  }
112
114
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"useQueries.js","names":[],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions\n }),\n [queries, client, isRestoring],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && options.subscribed !== false\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow?.error) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAAS,eAAe,WAAW;CACzC,MAAM,cAAc,eAAe;CACnC,MAAM,qBAAqB,2BAA2B;CAEtD,MAAM,mBAAmB,cAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA;EAEJ,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;CAAW,CAC/B;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,YAAY,eAEf,IAAI,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe,QAAQ,eAAe;CAC/D,qBACE,aACG,kBACC,kBACI,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,IAC1D,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,gBAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7D,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQ,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAI,cAAc,QAAQ,IAAI;GACpD,OAAO,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAA,sCAAA,QAAA,sCAAA,KAAA,IAAA,KAAA,IAAI,kCAAmC,OACrC,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
1
+ {"version":3,"file":"useQueries.js","names":[],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n const subscribed = options.subscribed !== false\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : subscribed\n ? 'optimistic'\n : undefined\n\n return defaultedOptions\n }),\n [queries, client, isRestoring, subscribed],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && subscribed\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAAS,eAAe,WAAW;CACzC,MAAM,cAAc,eAAe;CACnC,MAAM,qBAAqB,2BAA2B;CACtD,MAAM,aAAa,QAAQ,eAAe;CAE1C,MAAM,mBAAmB,cAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA,aACE,eACA,KAAA;EAEN,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;EAAa;CAAU,CAC3C;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,YAAY,eAEf,IAAI,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe;CACxC,qBACE,aACG,kBACC,kBACI,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,IAC1D,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,gBAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7D,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQ,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAI,cAAc,QAAQ,IAAI;GACpD,OAAO,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAI,mCACF,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
@@ -62,14 +62,16 @@ function useQueries({ queries, ...options }, queryClient) {
62
62
  const client = require_QueryClientProvider.useQueryClient(queryClient);
63
63
  const isRestoring = require_IsRestoringProvider.useIsRestoring();
64
64
  const errorResetBoundary = require_QueryErrorResetBoundary.useQueryErrorResetBoundary();
65
+ const subscribed = options.subscribed !== false;
65
66
  const defaultedQueries = (0, preact_hooks.useMemo)(() => queries.map((opts) => {
66
67
  const defaultedOptions = client.defaultQueryOptions(opts);
67
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
68
+ defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : subscribed ? "optimistic" : void 0;
68
69
  return defaultedOptions;
69
70
  }), [
70
71
  queries,
71
72
  client,
72
- isRestoring
73
+ isRestoring,
74
+ subscribed
73
75
  ]);
74
76
  defaultedQueries.forEach((queryOptions) => {
75
77
  require_suspense.ensureSuspenseTimers(queryOptions);
@@ -79,7 +81,7 @@ function useQueries({ queries, ...options }, queryClient) {
79
81
  require_errorBoundaryUtils.useClearResetErrorBoundary(errorResetBoundary);
80
82
  const [observer] = (0, preact_hooks.useState)(() => new _tanstack_query_core.QueriesObserver(client, defaultedQueries, options));
81
83
  const [optimisticResult, getCombinedResult, trackResult] = observer.getOptimisticResult(defaultedQueries, options.combine);
82
- const shouldSubscribe = !isRestoring && options.subscribed !== false;
84
+ const shouldSubscribe = !isRestoring && subscribed;
83
85
  require_utils.useSyncExternalStore((0, preact_hooks.useCallback)((onStoreChange) => shouldSubscribe ? observer.subscribe(_tanstack_query_core.notifyManager.batchCalls(onStoreChange)) : _tanstack_query_core.noop, [observer, shouldSubscribe]), () => observer.getCurrentResult());
84
86
  (0, preact_hooks.useEffect)(() => {
85
87
  observer.setQueries(defaultedQueries, options);
@@ -107,7 +109,7 @@ function useQueries({ queries, ...options }, queryClient) {
107
109
  suspense: query.suspense
108
110
  });
109
111
  });
110
- if (firstSingleResultWhichShouldThrow?.error) throw firstSingleResultWhichShouldThrow.error;
112
+ if (firstSingleResultWhichShouldThrow) throw firstSingleResultWhichShouldThrow.error;
111
113
  return getCombinedResult(trackResult());
112
114
  }
113
115
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"useQueries.cjs","names":["useQueryClient","useIsRestoring","useQueryErrorResetBoundary","useMemo","useState","QueriesObserver","useCallback","notifyManager","noop","shouldSuspend","QueryObserver","fetchOptimistic","getHasError"],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions\n }),\n [queries, client, isRestoring],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && options.subscribed !== false\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow?.error) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,MAAM,cAAcC,4BAAAA,eAAe;CACnC,MAAM,qBAAqBC,gCAAAA,2BAA2B;CAEtD,MAAM,oBAAA,GAAmBC,aAAAA,QAAAA,OAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA;EAEJ,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;CAAW,CAC/B;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,iBAAA,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,2BAAA,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAAA,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,aAAA,GAAYC,aAAAA,SAAAA,OAEf,IAAIC,qBAAAA,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe,QAAQ,eAAe;CAC/D,cAAA,sBAAA,GACEC,aAAAA,YAAAA,EACG,kBACC,kBACI,SAAS,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,IAC1DC,qBAAAA,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7DC,iBAAAA,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQA,iBAAAA,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAIC,qBAAAA,cAAc,QAAQ,IAAI;GACpD,OAAOC,iBAAAA,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACAC,2BAAAA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAI,mCAAmC,OACrC,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
1
+ {"version":3,"file":"useQueries.cjs","names":["useQueryClient","useIsRestoring","useQueryErrorResetBoundary","useMemo","useState","QueriesObserver","useCallback","notifyManager","noop","shouldSuspend","QueryObserver","fetchOptimistic","getHasError"],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n const subscribed = options.subscribed !== false\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : subscribed\n ? 'optimistic'\n : undefined\n\n return defaultedOptions\n }),\n [queries, client, isRestoring, subscribed],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && subscribed\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAASA,4BAAAA,eAAe,WAAW;CACzC,MAAM,cAAcC,4BAAAA,eAAe;CACnC,MAAM,qBAAqBC,gCAAAA,2BAA2B;CACtD,MAAM,aAAa,QAAQ,eAAe;CAE1C,MAAM,oBAAA,GAAmBC,aAAAA,QAAAA,OAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA,aACE,eACA,KAAA;EAEN,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;EAAa;CAAU,CAC3C;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,iBAAA,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,2BAAA,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAAA,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,aAAA,GAAYC,aAAAA,SAAAA,OAEf,IAAIC,qBAAAA,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe;CACxC,cAAA,sBAAA,GACEC,aAAAA,YAAAA,EACG,kBACC,kBACI,SAAS,UAAUC,qBAAAA,cAAc,WAAW,aAAa,CAAC,IAC1DC,qBAAAA,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,CAAA,GAAA,aAAA,UAAA,OAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7DC,iBAAAA,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQA,iBAAAA,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAIC,qBAAAA,cAAc,QAAQ,IAAI;GACpD,OAAOC,iBAAAA,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACAC,2BAAAA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAI,mCACF,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
@@ -61,14 +61,16 @@ function useQueries({ queries, ...options }, queryClient) {
61
61
  const client = useQueryClient(queryClient);
62
62
  const isRestoring = useIsRestoring();
63
63
  const errorResetBoundary = useQueryErrorResetBoundary();
64
+ const subscribed = options.subscribed !== false;
64
65
  const defaultedQueries = useMemo(() => queries.map((opts) => {
65
66
  const defaultedOptions = client.defaultQueryOptions(opts);
66
- defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : "optimistic";
67
+ defaultedOptions._optimisticResults = isRestoring ? "isRestoring" : subscribed ? "optimistic" : void 0;
67
68
  return defaultedOptions;
68
69
  }), [
69
70
  queries,
70
71
  client,
71
- isRestoring
72
+ isRestoring,
73
+ subscribed
72
74
  ]);
73
75
  defaultedQueries.forEach((queryOptions) => {
74
76
  ensureSuspenseTimers(queryOptions);
@@ -78,7 +80,7 @@ function useQueries({ queries, ...options }, queryClient) {
78
80
  useClearResetErrorBoundary(errorResetBoundary);
79
81
  const [observer] = useState(() => new QueriesObserver(client, defaultedQueries, options));
80
82
  const [optimisticResult, getCombinedResult, trackResult] = observer.getOptimisticResult(defaultedQueries, options.combine);
81
- const shouldSubscribe = !isRestoring && options.subscribed !== false;
83
+ const shouldSubscribe = !isRestoring && subscribed;
82
84
  useSyncExternalStore(useCallback((onStoreChange) => shouldSubscribe ? observer.subscribe(notifyManager.batchCalls(onStoreChange)) : noop, [observer, shouldSubscribe]), () => observer.getCurrentResult());
83
85
  useEffect(() => {
84
86
  observer.setQueries(defaultedQueries, options);
@@ -106,7 +108,7 @@ function useQueries({ queries, ...options }, queryClient) {
106
108
  suspense: query.suspense
107
109
  });
108
110
  });
109
- if (firstSingleResultWhichShouldThrow?.error) throw firstSingleResultWhichShouldThrow.error;
111
+ if (firstSingleResultWhichShouldThrow) throw firstSingleResultWhichShouldThrow.error;
110
112
  return getCombinedResult(trackResult());
111
113
  }
112
114
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"useQueries.js","names":[],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : 'optimistic'\n\n return defaultedOptions\n }),\n [queries, client, isRestoring],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && options.subscribed !== false\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow?.error) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAAS,eAAe,WAAW;CACzC,MAAM,cAAc,eAAe;CACnC,MAAM,qBAAqB,2BAA2B;CAEtD,MAAM,mBAAmB,cAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA;EAEJ,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;CAAW,CAC/B;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,YAAY,eAEf,IAAI,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe,QAAQ,eAAe;CAC/D,qBACE,aACG,kBACC,kBACI,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,IAC1D,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,gBAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7D,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQ,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAI,cAAc,QAAQ,IAAI;GACpD,OAAO,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAI,mCAAmC,OACrC,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
1
+ {"version":3,"file":"useQueries.js","names":[],"sources":["../../src/useQueries.ts"],"sourcesContent":["import {\n QueriesObserver,\n QueryObserver,\n noop,\n notifyManager,\n} from '@tanstack/query-core'\nimport type {\n DefaultError,\n OmitKeyof,\n QueriesObserverOptions,\n QueriesPlaceholderDataFunction,\n QueryClient,\n QueryFunction,\n QueryKey,\n QueryObserverOptions,\n ThrowOnError,\n} from '@tanstack/query-core'\nimport { useCallback, useEffect, useMemo, useState } from 'preact/hooks'\n\nimport { useIsRestoring } from './IsRestoringProvider'\nimport { useQueryClient } from './QueryClientProvider'\nimport { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'\nimport {\n ensurePreventErrorBoundaryRetry,\n getHasError,\n useClearResetErrorBoundary,\n} from './errorBoundaryUtils'\nimport {\n ensureSuspenseTimers,\n fetchOptimistic,\n shouldSuspend,\n} from './suspense'\nimport type {\n DefinedUseQueryResult,\n UseQueryOptions,\n UseQueryResult,\n} from './types'\nimport { useSyncExternalStore } from './utils'\n\n// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.\n// `placeholderData` function always gets undefined passed\ntype UseQueryOptionsForUseQueries<\n TQueryFnData = unknown,\n TError = DefaultError,\n TData = TQueryFnData,\n TQueryKey extends QueryKey = QueryKey,\n> = OmitKeyof<\n UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>,\n 'placeholderData' | 'subscribed'\n> & {\n placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>\n}\n\n// Avoid TS depth-limit error in case of large array literal\ntype MAXIMUM_DEPTH = 20\n\n// Widen the type of the symbol to enable type inference even if skipToken is not immutable.\ntype SkipTokenForUseQueries = symbol\n\ntype GetUseQueryOptionsForUseQueries<T> =\n // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }\n T extends {\n queryFnData: infer TQueryFnData\n error?: infer TError\n data: infer TData\n }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? UseQueryOptionsForUseQueries<unknown, TError, TData>\n : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]\n T extends [infer TQueryFnData, infer TError, infer TData]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError, TData>\n : T extends [infer TQueryFnData, infer TError]\n ? UseQueryOptionsForUseQueries<TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? UseQueryOptionsForUseQueries<TQueryFnData>\n : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, infer TQueryKey>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? UseQueryOptionsForUseQueries<\n TQueryFnData,\n unknown extends TError ? DefaultError : TError,\n unknown extends TData ? TQueryFnData : TData,\n TQueryKey\n >\n : // Fallback\n UseQueryOptionsForUseQueries\n\n// A defined initialData setting should return a DefinedUseQueryResult rather than UseQueryResult\ntype GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {\n initialData?: infer TInitialData\n}\n ? unknown extends TInitialData\n ? UseQueryResult<TData, TError>\n : TInitialData extends TData\n ? DefinedUseQueryResult<TData, TError>\n : TInitialData extends () => infer TInitialDataResult\n ? unknown extends TInitialDataResult\n ? UseQueryResult<TData, TError>\n : TInitialDataResult extends TData\n ? DefinedUseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n : UseQueryResult<TData, TError>\n\ntype GetUseQueryResult<T> =\n // Part 1: responsible for mapping explicit type parameter to function result, if object\n T extends { queryFnData: any; error?: infer TError; data: infer TData }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends { queryFnData: infer TQueryFnData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends { data: infer TData; error?: infer TError }\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : // Part 2: responsible for mapping explicit type parameter to function result, if tuple\n T extends [any, infer TError, infer TData]\n ? GetDefinedOrUndefinedQueryResult<T, TData, TError>\n : T extends [infer TQueryFnData, infer TError]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>\n : T extends [infer TQueryFnData]\n ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>\n : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided\n T extends {\n queryFn?:\n | QueryFunction<infer TQueryFnData, any>\n | SkipTokenForUseQueries\n select?: (data: any) => infer TData\n throwOnError?: ThrowOnError<any, infer TError, any, any>\n }\n ? GetDefinedOrUndefinedQueryResult<\n T,\n unknown extends TData ? TQueryFnData : TData,\n unknown extends TError ? DefaultError : TError\n >\n : // Fallback\n UseQueryResult\n\n/**\n * The `queries` array accepted by `useQueries`. Recursively unwraps each tuple element so every entry's\n * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements. An opaque array (e.g.\n * `unknown[]`) is returned as-is; a non-tuple array of a known element type, or a tuple past 20 elements, falls\n * back to a single homogeneous options type.\n *\n * @template T - The type of the `queries` array as written at the call site.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesOptions<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryOptionsForUseQueries>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryOptionsForUseQueries<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesOptions<\n [...Tails],\n [...TResults, GetUseQueryOptionsForUseQueries<Head>],\n [...TDepth, 1]\n >\n : ReadonlyArray<unknown> extends T\n ? T\n : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!\n // use this to infer the param types in the case of Array.map() argument\n T extends Array<\n UseQueryOptionsForUseQueries<\n infer TQueryFnData,\n infer TError,\n infer TData,\n infer TQueryKey\n >\n >\n ? Array<\n UseQueryOptionsForUseQueries<\n TQueryFnData,\n TError,\n TData,\n TQueryKey\n >\n >\n : // Fallback\n Array<UseQueryOptionsForUseQueries>\n\n/**\n * The result type returned by `useQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}: each\n * tuple element's result type is inferred individually, up to 20 elements. A non-tuple array is mapped\n * per-element instead, still inferring each entry individually; only past 20 elements does this fall back to a\n * single homogeneous {@link UseQueryResult} type.\n *\n * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.\n * @template TResults - The internal accumulator that this type builds during recursion. It is not meant\n * to be set explicitly.\n * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not\n * meant to be set explicitly.\n */\nexport type QueriesResults<\n T extends Array<any>,\n TResults extends Array<any> = [],\n TDepth extends ReadonlyArray<number> = [],\n> = TDepth['length'] extends MAXIMUM_DEPTH\n ? Array<UseQueryResult>\n : T extends []\n ? []\n : T extends [infer Head]\n ? [...TResults, GetUseQueryResult<Head>]\n : T extends [infer Head, ...infer Tails]\n ? QueriesResults<\n [...Tails],\n [...TResults, GetUseQueryResult<Head>],\n [...TDepth, 1]\n >\n : { [K in keyof T]: GetUseQueryResult<T[K]> }\n\n/**\n * The `useQueries` hook can be used to fetch a variable number of queries.\n *\n * The `queries` key accepts an array with query option objects identical to `useQuery` (excluding the\n * `queryClient` option - because the `QueryClient` can be passed in on the top level).\n *\n * Having the same query key more than once in the array of query objects may cause some data to be shared\n * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired\n * structure.\n *\n * The `combine` option can be used to combine the results of the queries into a single value. The result will\n * be structurally shared to be as referentially stable as possible.\n *\n * @param queryClient - Use this to provide a custom `QueryClient`. Otherwise, the one from the nearest context\n * will be used.\n * @returns The combined result. Without `combine`, this is an array with all the query results, in the same\n * order as the input. When `combine` is provided, this is the value returned by `combine` instead.\n *\n * @example\n * ```tsx\n * import { useQueries } from '@tanstack/preact-query'\n *\n * const ids = [1, 2, 3]\n * const results = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * staleTime: Infinity,\n * })),\n * })\n * ```\n *\n * @example\n * Combining results into a single value:\n * ```tsx\n * const ids = [1, 2, 3]\n * const combinedQueries = useQueries({\n * queries: ids.map((id) => ({\n * queryKey: ['post', id],\n * queryFn: () => fetchPost(id),\n * })),\n * combine: (results) => {\n * return {\n * data: results.map((result) => result.data),\n * pending: results.some((result) => result.isPending),\n * }\n * },\n * })\n * ```\n */\nexport function useQueries<\n T extends Array<any>,\n TCombinedResult = QueriesResults<T>,\n>(\n {\n queries,\n ...options\n }: {\n /**\n * An array with query option objects, mostly identical to `useQuery` — except that `queryClient` and\n * `subscribed` aren't accepted per-query (`subscribed` is a top-level option here instead), and\n * `placeholderData` accepts a {@link QueriesPlaceholderDataFunction}, which is called with `previousData`\n * and `previousQuery` always `undefined`, rather than `useQuery`'s placeholder function.\n */\n queries:\n | readonly [...QueriesOptions<T>]\n | readonly [...{ [K in keyof T]: GetUseQueryOptionsForUseQueries<T[K]> }]\n /**\n * Use this to combine the results of the queries into a single value. The result will be structurally\n * shared to be as referentially stable as possible.\n */\n combine?: (result: QueriesResults<T>) => TCombinedResult\n /**\n * Set this to `false` to unsubscribe this observer from updates to the query cache.\n *\n * @defaultValue true\n */\n subscribed?: boolean\n },\n queryClient?: QueryClient,\n): TCombinedResult {\n const client = useQueryClient(queryClient)\n const isRestoring = useIsRestoring()\n const errorResetBoundary = useQueryErrorResetBoundary()\n const subscribed = options.subscribed !== false\n\n const defaultedQueries = useMemo(\n () =>\n queries.map((opts) => {\n const defaultedOptions = client.defaultQueryOptions(\n opts as QueryObserverOptions,\n )\n\n // Make sure the results are already in fetching state before subscribing or updating options\n defaultedOptions._optimisticResults = isRestoring\n ? 'isRestoring'\n : subscribed\n ? 'optimistic'\n : undefined\n\n return defaultedOptions\n }),\n [queries, client, isRestoring, subscribed],\n )\n\n defaultedQueries.forEach((queryOptions) => {\n ensureSuspenseTimers(queryOptions)\n const query = client.getQueryCache().get(queryOptions.queryHash)\n ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)\n })\n\n useClearResetErrorBoundary(errorResetBoundary)\n\n const [observer] = useState(\n () =>\n new QueriesObserver<TCombinedResult>(\n client,\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n ),\n )\n\n // note: this must be called before useSyncExternalStore\n const [optimisticResult, getCombinedResult, trackResult] =\n observer.getOptimisticResult(\n defaultedQueries,\n (options as QueriesObserverOptions<TCombinedResult>).combine,\n )\n\n const shouldSubscribe = !isRestoring && subscribed\n useSyncExternalStore(\n useCallback(\n (onStoreChange) =>\n shouldSubscribe\n ? observer.subscribe(notifyManager.batchCalls(onStoreChange))\n : noop,\n [observer, shouldSubscribe],\n ),\n () => observer.getCurrentResult(),\n )\n\n useEffect(() => {\n observer.setQueries(\n defaultedQueries,\n options as QueriesObserverOptions<TCombinedResult>,\n )\n }, [defaultedQueries, options, observer])\n\n const shouldAtLeastOneSuspend = optimisticResult.some((result, index) =>\n shouldSuspend(defaultedQueries[index], result),\n )\n\n const suspensePromises = shouldAtLeastOneSuspend\n ? optimisticResult.flatMap((result, index) => {\n const opts = defaultedQueries[index]\n\n if (opts && shouldSuspend(opts, result)) {\n const queryObserver = new QueryObserver(client, opts)\n return fetchOptimistic(opts, queryObserver, errorResetBoundary)\n }\n return []\n })\n : []\n\n if (suspensePromises.length > 0) {\n throw Promise.all(suspensePromises)\n }\n const firstSingleResultWhichShouldThrow = optimisticResult.find(\n (result, index) => {\n const query = defaultedQueries[index]\n return (\n query &&\n getHasError({\n result,\n errorResetBoundary,\n throwOnError: query.throwOnError,\n query: client.getQueryCache().get(query.queryHash),\n suspense: query.suspense,\n })\n )\n },\n )\n\n if (firstSingleResultWhichShouldThrow) {\n throw firstSingleResultWhichShouldThrow.error\n }\n\n return getCombinedResult(trackResult())\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkRA,SAAgB,WAId,EACE,SACA,GAAG,WAuBL,aACiB;CACjB,MAAM,SAAS,eAAe,WAAW;CACzC,MAAM,cAAc,eAAe;CACnC,MAAM,qBAAqB,2BAA2B;CACtD,MAAM,aAAa,QAAQ,eAAe;CAE1C,MAAM,mBAAmB,cAErB,QAAQ,KAAK,SAAS;EACpB,MAAM,mBAAmB,OAAO,oBAC9B,IACF;EAGA,iBAAiB,qBAAqB,cAClC,gBACA,aACE,eACA,KAAA;EAEN,OAAO;CACT,CAAC,GACH;EAAC;EAAS;EAAQ;EAAa;CAAU,CAC3C;CAEA,iBAAiB,SAAS,iBAAiB;EACzC,qBAAqB,YAAY;EACjC,MAAM,QAAQ,OAAO,cAAc,CAAC,CAAC,IAAI,aAAa,SAAS;EAC/D,gCAAgC,cAAc,oBAAoB,KAAK;CACzE,CAAC;CAED,2BAA2B,kBAAkB;CAE7C,MAAM,CAAC,YAAY,eAEf,IAAI,gBACF,QACA,kBACA,OACF,CACJ;CAGA,MAAM,CAAC,kBAAkB,mBAAmB,eAC1C,SAAS,oBACP,kBACC,QAAoD,OACvD;CAEF,MAAM,kBAAkB,CAAC,eAAe;CACxC,qBACE,aACG,kBACC,kBACI,SAAS,UAAU,cAAc,WAAW,aAAa,CAAC,IAC1D,MACN,CAAC,UAAU,eAAe,CAC5B,SACM,SAAS,iBAAiB,CAClC;CAEA,gBAAgB;EACd,SAAS,WACP,kBACA,OACF;CACF,GAAG;EAAC;EAAkB;EAAS;CAAQ,CAAC;CAMxC,MAAM,mBAJ0B,iBAAiB,MAAM,QAAQ,UAC7D,cAAc,iBAAiB,QAAQ,MAAM,CAGA,IAC3C,iBAAiB,SAAS,QAAQ,UAAU;EAC1C,MAAM,OAAO,iBAAiB;EAE9B,IAAI,QAAQ,cAAc,MAAM,MAAM,GAAG;GACvC,MAAM,gBAAgB,IAAI,cAAc,QAAQ,IAAI;GACpD,OAAO,gBAAgB,MAAM,eAAe,kBAAkB;EAChE;EACA,OAAO,CAAC;CACV,CAAC,IACD,CAAC;CAEL,IAAI,iBAAiB,SAAS,GAC5B,MAAM,QAAQ,IAAI,gBAAgB;CAEpC,MAAM,oCAAoC,iBAAiB,MACxD,QAAQ,UAAU;EACjB,MAAM,QAAQ,iBAAiB;EAC/B,OACE,SACA,YAAY;GACV;GACA;GACA,cAAc,MAAM;GACpB,OAAO,OAAO,cAAc,CAAC,CAAC,IAAI,MAAM,SAAS;GACjD,UAAU,MAAM;EAClB,CAAC;CAEL,CACF;CAEA,IAAI,mCACF,MAAM,kCAAkC;CAG1C,OAAO,kBAAkB,YAAY,CAAC;AACxC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/preact-query",
3
- "version": "5.102.6",
3
+ "version": "5.102.8",
4
4
  "description": "Hooks for managing, caching and syncing asynchronous and remote data in preact",
5
5
  "author": "tannerlinsley",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  "!build/codemods/**/__tests__"
44
44
  ],
45
45
  "dependencies": {
46
- "@tanstack/query-core": "5.102.6"
46
+ "@tanstack/query-core": "5.102.8"
47
47
  },
48
48
  "devDependencies": {
49
49
  "@preact/preset-vite": "^2.10.2",
@@ -55,7 +55,7 @@
55
55
  "preact-render-to-string": "^6.6.4",
56
56
  "typescript": "6.0.3",
57
57
  "typescript-eslint": "^8.54.0",
58
- "@tanstack/query-persist-client-core": "5.102.6",
58
+ "@tanstack/query-persist-client-core": "5.102.8",
59
59
  "@tanstack/query-test-utils": "0.0.0"
60
60
  },
61
61
  "peerDependencies": {
package/src/useQueries.ts CHANGED
@@ -306,6 +306,7 @@ export function useQueries<
306
306
  const client = useQueryClient(queryClient)
307
307
  const isRestoring = useIsRestoring()
308
308
  const errorResetBoundary = useQueryErrorResetBoundary()
309
+ const subscribed = options.subscribed !== false
309
310
 
310
311
  const defaultedQueries = useMemo(
311
312
  () =>
@@ -317,11 +318,13 @@ export function useQueries<
317
318
  // Make sure the results are already in fetching state before subscribing or updating options
318
319
  defaultedOptions._optimisticResults = isRestoring
319
320
  ? 'isRestoring'
320
- : 'optimistic'
321
+ : subscribed
322
+ ? 'optimistic'
323
+ : undefined
321
324
 
322
325
  return defaultedOptions
323
326
  }),
324
- [queries, client, isRestoring],
327
+ [queries, client, isRestoring, subscribed],
325
328
  )
326
329
 
327
330
  defaultedQueries.forEach((queryOptions) => {
@@ -348,7 +351,7 @@ export function useQueries<
348
351
  (options as QueriesObserverOptions<TCombinedResult>).combine,
349
352
  )
350
353
 
351
- const shouldSubscribe = !isRestoring && options.subscribed !== false
354
+ const shouldSubscribe = !isRestoring && subscribed
352
355
  useSyncExternalStore(
353
356
  useCallback(
354
357
  (onStoreChange) =>
@@ -402,7 +405,7 @@ export function useQueries<
402
405
  },
403
406
  )
404
407
 
405
- if (firstSingleResultWhichShouldThrow?.error) {
408
+ if (firstSingleResultWhichShouldThrow) {
406
409
  throw firstSingleResultWhichShouldThrow.error
407
410
  }
408
411