diff --git a/.changeset/adapter-error-boundary-options.md b/.changeset/adapter-error-boundary-options.md new file mode 100644 index 00000000000..57af6c97491 --- /dev/null +++ b/.changeset/adapter-error-boundary-options.md @@ -0,0 +1,16 @@ +--- +'@tanstack/angular-query': major +'@tanstack/lit-query': major +'@tanstack/preact-query': major +'@tanstack/query-core': major +'@tanstack/react-query': major +'@tanstack/solid-query': major +'@tanstack/svelte-query': major +'@tanstack/vue-query': major +--- + +Move error boundary options out of query-core. React, Preact, Solid, and Vue still accept `throwOnError` in their adapter options and client defaults. Import `QueryClient` from the adapter to configure those defaults. Imperative refetch methods still accept `throwOnError` to control promise rejection. + +Query observers now notify listeners when the result's error changes, even when the component does not track `error`. Set `notifyOnChangeProps: 'none'` to suppress all notifications and opt out of the query's `throwOnError` boundary handling. + +In React and Preact, `useQueries` skips `combine` when a query error needs to reach the error boundary. diff --git a/.changeset/adapter-suspense-policy.md b/.changeset/adapter-suspense-policy.md new file mode 100644 index 00000000000..d96665f4e63 --- /dev/null +++ b/.changeset/adapter-suspense-policy.md @@ -0,0 +1,10 @@ +--- +'@tanstack/query-core': major +'@tanstack/react-query': major +'@tanstack/preact-query': major +'@tanstack/lit-query': major +'@tanstack/svelte-query': major +'@tanstack/vue-query': major +--- + +Remove the `suspense` observer option from query-core. React and Preact select Suspense behavior through their dedicated hooks. diff --git a/.changeset/query-core-queries-observer-throw-on-error.md b/.changeset/query-core-queries-observer-throw-on-error.md deleted file mode 100644 index cac4c10bde2..00000000000 --- a/.changeset/query-core-queries-observer-throw-on-error.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -'@tanstack/query-core': patch ---- - -fix(query-core/queriesObserver): notify listeners when a query with 'throwOnError' fails even if the combined result does not change diff --git a/.changeset/static-notification-modes.md b/.changeset/static-notification-modes.md index 03496f23120..38f3540cd58 100644 --- a/.changeset/static-notification-modes.md +++ b/.changeset/static-notification-modes.md @@ -10,6 +10,6 @@ Limit `notifyOnChangeProps` to the static values `'all'` and `'none'`. -Replace `[]` with `'none'` to suppress observer notifications while the query stays subscribed and can fetch. Error changes still notify the observer when `throwOnError` is set. Keep `'all'` to receive every result change. +Replace `[]` with `'none'` to suppress observer notifications while the query stays subscribed and can fetch. Keep `'all'` to receive every result change. For non-empty lists or callbacks, omit the option to use the adapter's default or choose a static value. In React Native, use `subscribed: isFocused` if the screen can unsubscribe when it loses focus. diff --git a/docs/framework/react/guides/render-optimizations.md b/docs/framework/react/guides/render-optimizations.md index 90b822c1a80..88ad862c1c6 100644 --- a/docs/framework/react/guides/render-optimizations.md +++ b/docs/framework/react/guides/render-optimizations.md @@ -34,9 +34,9 @@ The top level object returned from `useQuery`, `useInfiniteQuery`, `useMutation` ## tracked properties -React Query will only trigger a re-render if one of the properties returned from `useQuery` is actually "used". This is done by using [Proxy object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). This avoids a lot of unnecessary re-renders, e.g. because properties like `isFetching` or `isStale` might change often, but are not used in the component. +React Query tracks which `useQuery` result properties the component reads with a [Proxy object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy). This avoids re-renders when unused properties such as `isFetching` or `isStale` change. -Set `notifyOnChangeProps: 'all'` to notify the component whenever the query result changes. Set `notifyOnChangeProps: 'none'` to suppress these notifications while the query can still fetch. If you set `throwOnError`, changes to the error still notify the component. You can set these options in the query defaults or on individual queries. +Changes to the query error notify the component even if it does not read `error`. Set `notifyOnChangeProps: 'all'` to receive every result change. Set `notifyOnChangeProps: 'none'` to suppress result notifications and disable `throwOnError` for that observer. The query can still fetch. You can set these options in the query defaults or on individual queries. > Note: The get trap of a proxy is invoked by accessing a property, either via destructuring or by accessing it directly. If you use object rest destructuring, you will disable this optimization. We have a [lint rule](../../../eslint/no-rest-destructuring.md) to guard against this pitfall. diff --git a/packages/angular-query/src/__tests__/inject-mutation.test.ts b/packages/angular-query/src/__tests__/inject-mutation.test.ts index 28b94607d92..a4ef400b4b8 100644 --- a/packages/angular-query/src/__tests__/inject-mutation.test.ts +++ b/packages/angular-query/src/__tests__/inject-mutation.test.ts @@ -45,7 +45,6 @@ describe('injectMutation', () => { it('publishes mutation failures to observers and cache signals without global reporting', async () => { vi.useRealTimers() - queryClient.setDefaultOptions({ mutations: { throwOnError: true } }) const cacheReport = vi.fn<(error: Error) => void>() queryClient.getMutationCache().config.onError = cacheReport const report = vi.spyOn(TestBed.inject(ErrorHandler), 'handleError') diff --git a/packages/angular-query/src/__tests__/inject-queries.test.ts b/packages/angular-query/src/__tests__/inject-queries.test.ts index 5f5f9cd9cc3..79f932e83ae 100644 --- a/packages/angular-query/src/__tests__/inject-queries.test.ts +++ b/packages/angular-query/src/__tests__/inject-queries.test.ts @@ -75,7 +75,7 @@ describe('injectQueries', () => { it('should keep failed refetch state and cached data readable without global reporting', async () => { vi.useRealTimers() queryClient.setDefaultOptions({ - queries: { retry: false, throwOnError: true }, + queries: { retry: false }, }) const report = vi.spyOn(TestBed.inject(ErrorHandler), 'handleError') const error = new Error('query failed') diff --git a/packages/angular-query/src/__tests__/inject-query.test.ts b/packages/angular-query/src/__tests__/inject-query.test.ts index a3a69e876c3..c4f2f605121 100644 --- a/packages/angular-query/src/__tests__/inject-query.test.ts +++ b/packages/angular-query/src/__tests__/inject-query.test.ts @@ -66,7 +66,7 @@ describe('injectQuery', () => { it('should keep failed refetch state and cached data readable without global reporting', async () => { vi.useRealTimers() queryClient.setDefaultOptions({ - queries: { retry: false, throwOnError: true }, + queries: { retry: false }, }) const report = vi.spyOn(TestBed.inject(ErrorHandler), 'handleError') const error = new Error('query failed') diff --git a/packages/angular-query/src/types.ts b/packages/angular-query/src/types.ts index 89cbac29325..bff47f6cc4c 100644 --- a/packages/angular-query/src/types.ts +++ b/packages/angular-query/src/types.ts @@ -27,9 +27,8 @@ type SignalFunction any> = T & Signal> /** * The options accepted by `injectQuery`, with cache data projected through an optional `select`. Same as - * {@link QueryObserverOptions} from `@tanstack/query-core`, minus `notifyOnChangeProps`, `suspense`, and - * `throwOnError`: Angular owns result notifications and exposes errors through signals rather than error - * boundaries. + * {@link QueryObserverOptions} from `@tanstack/query-core`, minus `notifyOnChangeProps`. Angular owns result + * notifications and exposes errors through signals. * @template TQueryFnData - The type your `queryFn` resolves to. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no @@ -43,7 +42,7 @@ export type CreateQueryOptions< TQueryKey extends QueryKey = QueryKey, > = OmitKeyof< QueryObserverOptions, - 'notifyOnChangeProps' | 'suspense' | 'throwOnError' + 'notifyOnChangeProps' > type CreateStatusBasedQueryResult< @@ -232,8 +231,7 @@ export interface DefinedInfiniteQueryNarrowing< /** * The options accepted by `injectInfiniteQuery`, including page parameters and pagination callbacks. Same as * {@link InfiniteQueryObserverOptions} from `@tanstack/query-core` — for the infinite-query-specific options - * (`getNextPageParam`, `initialPageParam`, etc.) — minus `notifyOnChangeProps`, `suspense`, and - * `throwOnError`, like {@link CreateQueryOptions}. + * (`getNextPageParam`, `initialPageParam`, etc.) — minus `notifyOnChangeProps`, like {@link CreateQueryOptions}. * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` here, though @@ -256,7 +254,7 @@ export interface CreateInfiniteQueryOptions< TQueryKey, TPageParam >, - 'notifyOnChangeProps' | 'suspense' | 'throwOnError' + 'notifyOnChangeProps' > {} /** @@ -359,7 +357,7 @@ export interface CreateMutationOptions< TOnMutateResult = unknown, > extends OmitKeyof< MutationObserverOptions, - '_defaulted' | 'throwOnError' + '_defaulted' > {} /** diff --git a/packages/lit-query/src/__tests__/createQueriesController.test-d.ts b/packages/lit-query/src/__tests__/createQueriesController.test-d.ts index eabc9548c0d..4f4c671d0fa 100644 --- a/packages/lit-query/src/__tests__/createQueriesController.test-d.ts +++ b/packages/lit-query/src/__tests__/createQueriesController.test-d.ts @@ -562,7 +562,7 @@ describe('createQueriesController', () => { const key5 = createKey() type BizError = { code: number } - const throwOnError = (_error: BizError) => true + const retry = (_failureCount: number, _error: BizError) => true // Array.map preserves TQueryFnData const result1 = createQueriesController( @@ -589,7 +589,7 @@ describe('createQueriesController', () => { queries: Array(50).map((_, i) => ({ queryKey: ['key', i] as const, queryFn: () => i + 10, - throwOnError, + retry, })), }, new QueryClient(), @@ -625,7 +625,7 @@ describe('createQueriesController', () => { queryKey: ['key', i] as const, queryFn: () => i + 10, select: (data: number) => data.toString(), - throwOnError, + retry, })), }, new QueryClient(), @@ -654,7 +654,7 @@ describe('createQueriesController', () => { { queryKey: key5, queryFn: () => 'string', - throwOnError, + retry, }, ], }, @@ -674,7 +674,7 @@ describe('createQueriesController', () => { expectTypeOf(result3[3].data).toEqualTypeOf() // select takes precedence over queryFn expectTypeOf(result3[2].data).toEqualTypeOf() - // infer TError from throwOnError + // infer TError from retry expectTypeOf(result3[3].error).toEqualTypeOf() // initialData/placeholderData are enforced @@ -701,7 +701,7 @@ describe('createQueriesController', () => { new QueryClient(), )() - // select and throwOnError params are "indirectly" enforced + // select and retry params are "indirectly" enforced createQueriesController( new Host(), { @@ -729,7 +729,7 @@ describe('createQueriesController', () => { { queryKey: key5, queryFn: () => 'string', - throwOnError, + retry, }, ], }, @@ -782,7 +782,7 @@ describe('createQueriesController', () => { queryKey: key5, queryFn: () => 'string', select: (a: string) => parseInt(a), - throwOnError, + retry, }, ], }, @@ -834,7 +834,7 @@ describe('createQueriesController', () => { { queryKey: key5, queryFn: () => 'string', - throwOnError, + retry, }, ], } as const, diff --git a/packages/lit-query/src/createQueriesController.ts b/packages/lit-query/src/createQueriesController.ts index 17e03038bdb..21ce76f3cb3 100644 --- a/packages/lit-query/src/createQueriesController.ts +++ b/packages/lit-query/src/createQueriesController.ts @@ -13,7 +13,6 @@ import type { QueryKey, QueryObserverOptions, QueryObserverResult, - ThrowOnError, } from '@tanstack/query-core' import type { ReactiveControllerHost } from 'lit' import type { Accessor, ValueAccessor } from './accessor.js' @@ -63,7 +62,10 @@ type GetCreateQueriesInput = T extends { | QueryFunction | SkipTokenForCreateQueries select?: (data: any) => infer TData - throwOnError?: ThrowOnError + retry?: + | boolean + | number + | ((failureCount: number, error: infer TError) => boolean) } ? CreateQueriesInputForController< TQueryFnData, @@ -114,7 +116,10 @@ type GetCreateQueriesResult = T extends { | QueryFunction | SkipTokenForCreateQueries select?: (data: any) => infer TData - throwOnError?: ThrowOnError + retry?: + | boolean + | number + | ((failureCount: number, error: infer TError) => boolean) } ? GetDefinedOrUndefinedCreateQueriesResult< T, diff --git a/packages/preact-query/src/QueryClient.ts b/packages/preact-query/src/QueryClient.ts new file mode 100644 index 00000000000..967601966d4 --- /dev/null +++ b/packages/preact-query/src/QueryClient.ts @@ -0,0 +1,88 @@ +import { QueryClient as CoreQueryClient } from '@tanstack/query-core' +import type { + DefaultOptions as CoreDefaultOptions, + QueryClientConfig as CoreQueryClientConfig, + DefaultError, + MutationKey, + QueryKey, +} from '@tanstack/query-core' +import type { + ThrowOnError, + UseBaseQueryOptions, + UseMutationOptions, +} from './types' + +/** Client defaults, including the adapter's error boundary options. */ +export interface DefaultOptions< + TError = DefaultError, +> extends CoreDefaultOptions { + /** Default query options, including whether to throw errors to an error boundary. */ + queries?: CoreDefaultOptions['queries'] & + Pick, 'throwOnError'> + /** Default mutation options, including whether to throw errors to an error boundary. */ + mutations?: CoreDefaultOptions['mutations'] & + Pick, 'throwOnError'> +} + +/** Configuration for a query client with adapter-specific defaults. */ +export interface QueryClientConfig extends CoreQueryClientConfig { + /** Default options for all queries and mutations created through this client. */ + defaultOptions?: DefaultOptions +} + +/** A query client that accepts the adapter's error boundary options as defaults. */ +export interface QueryClient extends CoreQueryClient { + /** {@inheritDoc CoreQueryClient.getDefaultOptions} */ + getDefaultOptions: () => DefaultOptions + /** {@inheritDoc CoreQueryClient.setDefaultOptions} */ + setDefaultOptions: (options: DefaultOptions) => void + + /** {@inheritDoc CoreQueryClient.setQueryDefaults} */ + setQueryDefaults: < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + >( + queryKey: QueryKey, + options: Partial< + Omit< + UseBaseQueryOptions, + 'queryKey' | 'subscribed' + > + >, + ) => void + + /** {@inheritDoc CoreQueryClient.getQueryDefaults} */ + getQueryDefaults: (queryKey: QueryKey) => ReturnType< + CoreQueryClient['getQueryDefaults'] + > & { + throwOnError?: ThrowOnError + } + + /** {@inheritDoc CoreQueryClient.setMutationDefaults} */ + setMutationDefaults: < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + mutationKey: MutationKey, + options: Omit< + UseMutationOptions, + 'mutationKey' + >, + ) => void + + /** {@inheritDoc CoreQueryClient.getMutationDefaults} */ + getMutationDefaults: ( + mutationKey: MutationKey, + ) => ReturnType & + Pick, 'throwOnError'> +} + +/** Creates a query client. The constructor is shared with query-core. */ +export const QueryClient: { + new (config?: QueryClientConfig): QueryClient + readonly prototype: QueryClient +} = CoreQueryClient diff --git a/packages/preact-query/src/QueryClientProvider.tsx b/packages/preact-query/src/QueryClientProvider.tsx index 4cfc74eb844..0c402b172f1 100644 --- a/packages/preact-query/src/QueryClientProvider.tsx +++ b/packages/preact-query/src/QueryClientProvider.tsx @@ -1,7 +1,7 @@ import { createContext } from 'preact' import { useContext, useEffect } from 'preact/hooks' -import type { QueryClient } from '@tanstack/query-core' import type { ComponentChildren, VNode } from 'preact' +import type { QueryClient } from './QueryClient' /** * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. diff --git a/packages/preact-query/src/__tests__/useQueries.test.tsx b/packages/preact-query/src/__tests__/useQueries.test.tsx index 2a674d21e6e..4cc8015be1f 100644 --- a/packages/preact-query/src/__tests__/useQueries.test.tsx +++ b/packages/preact-query/src/__tests__/useQueries.test.tsx @@ -473,48 +473,83 @@ describe('useQueries', () => { expect(rendered.getByText('error boundary')).toBeInTheDocument() }) - it("should throw error if in one of queries' queryFn throws and throwOnError is in use while the combined result does not change", async () => { + it('sends an error to the boundary when combined data stays the same', async () => { vi.spyOn(console, 'error').mockReturnValue(undefined) - const key = createKey() + const queryKey = createKey() function Page() { const data = useQueries({ queries: [ { - queryKey: key, + queryKey, queryFn: () => - sleep(10).then(() => - Promise.reject(new Error('single query error')), - ), - throwOnError: true, + sleep(10).then(() => { + throw new Error('query failed') + }), retry: false, + throwOnError: true, }, ], combine: (results) => results.map((result) => result.data), }) - return
data: {String(data[0])}
} const rendered = renderWithClient( queryClient, - ( -
-
error boundary
-
{error.message}
-
- )} - > +
{error.message}
}>
, ) expect(rendered.getByText('data: undefined')).toBeInTheDocument() + await vi.advanceTimersByTimeAsync(10) + expect(rendered.getByText('query failed')).toBeInTheDocument() + }) - await vi.advanceTimersByTimeAsync(11) - expect(rendered.getByText('error boundary')).toBeInTheDocument() - expect(rendered.getByText('single query error')).toBeInTheDocument() + it('reports the query error before calling combine with a failed result', async () => { + vi.spyOn(console, 'error').mockReturnValue(undefined) + const queryKey = createKey() + const queryError = new Error('query failed') + const queryFn = () => Promise.reject(queryError) + const onError = vi.fn<(error: Error) => void>() + queryCache.config.onError = onError + + function Page() { + const data = useQueries({ + queries: [ + { + queryKey, + queryFn, + enabled: false, + retry: false, + throwOnError: true, + }, + ], + combine: ([result]) => { + if (result.isError) { + throw new Error('combine received a failed result') + } + return result.data + }, + }) + return
data: {String(data)}
+ } + + const rendered = renderWithClient( + queryClient, +
{error.message}
}> + +
, + ) + + expect(rendered.getByText('data: undefined')).toBeInTheDocument() + await expect( + queryClient.query({ queryKey, queryFn, retry: false }), + ).rejects.toBe(queryError) + await vi.advanceTimersByTimeAsync(0) + expect(onError).toHaveBeenCalledWith(queryError, expect.anything()) + expect(rendered.getByText('query failed')).toBeInTheDocument() }) it('should use provided custom queryClient', async () => { diff --git a/packages/preact-query/src/__tests__/useQuery.test.tsx b/packages/preact-query/src/__tests__/useQuery.test.tsx index 4724214cdc4..fde83c1fdc7 100644 --- a/packages/preact-query/src/__tests__/useQuery.test.tsx +++ b/packages/preact-query/src/__tests__/useQuery.test.tsx @@ -2655,36 +2655,46 @@ describe('useQuery', () => { expect(rendered.getByText('Error test')).toBeInTheDocument() }) - it('should throw error if queryFn throws and throwOnError is in use', async () => { - vi.spyOn(console, 'error').mockReturnValue(undefined) - const key = createKey() + it.each([ + { notifyOnChangeProps: undefined, expected: 'error boundary' }, + { notifyOnChangeProps: 'none', expected: 'Error test' }, + ] as const)( + 'shows $expected with notifyOnChangeProps set to $notifyOnChangeProps', + async ({ notifyOnChangeProps, expected }) => { + vi.spyOn(console, 'error').mockReturnValue(undefined) + const key = createKey() + const throwOnError = vi.fn<() => boolean>(() => true) + const queryFn = async () => { + throw new Error('Error test') + } + queryClient.setQueryDefaults(key, { throwOnError }) + await expect( + queryClient.query({ queryKey: key, queryFn, retry: false }), + ).rejects.toThrow('Error test') - function Page() { - const { status, error } = useQuery({ - queryKey: key, - queryFn: () => Promise.reject(new Error('Error test')), - retry: false, - throwOnError: true, - }) + function Page() { + const { error } = useQuery({ + queryKey: key, + queryFn, + enabled: false, + notifyOnChangeProps, + }) + return
{error?.message}
+ } - return ( -
-

{status}

-

{error}

-
+ const rendered = renderWithClient( + queryClient, +
error boundary
}> + +
, ) - } - - const rendered = renderWithClient( - queryClient, -
error boundary
}> - -
, - ) - await vi.advanceTimersByTimeAsync(0) - expect(rendered.getByText('error boundary')).toBeInTheDocument() - }) + expect(rendered.getByText(expected)).toBeInTheDocument() + expect(throwOnError.mock.calls.length === 0).toBe( + notifyOnChangeProps === 'none', + ) + }, + ) it('should throw error if queryFn rejects with a falsy error and throwOnError is in use', async () => { vi.spyOn(console, 'error').mockReturnValue(undefined) diff --git a/packages/preact-query/src/errorBoundaryUtils.ts b/packages/preact-query/src/errorBoundaryUtils.ts index cf02dcc1fa2..1085edf38af 100644 --- a/packages/preact-query/src/errorBoundaryUtils.ts +++ b/packages/preact-query/src/errorBoundaryUtils.ts @@ -1,13 +1,8 @@ -import { shouldThrowError } from '@tanstack/query-core' import { useEffect } from 'preact/hooks' -import type { - DefaultedQueryObserverOptions, - Query, - QueryKey, - QueryObserverResult, - ThrowOnError, -} from '@tanstack/query-core' +import { shouldThrowError } from './utils' +import type { Query, QueryKey, QueryObserverResult } from '@tanstack/query-core' import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { DefaultedQueryOptions, ThrowOnError } from './types' /** * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), @@ -16,15 +11,16 @@ import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' * @param options - The defaulted query options to adjust. * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. * @param query - The query, used to evaluate a `throwOnError` function against its error. + * @param suspense - Whether the hook uses Suspense. */ -export const ensurePreventErrorBoundaryRetry = < +export const prepareErrorBoundaryOptions = < TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, >( - options: DefaultedQueryObserverOptions< + options: DefaultedQueryOptions< TQueryFnData, TError, TData, @@ -33,7 +29,12 @@ export const ensurePreventErrorBoundaryRetry = < >, errorResetBoundary: QueryErrorResetBoundaryValue, query: Query | undefined, + suspense: boolean, ) => { + if (options.notifyOnChangeProps === 'none') { + options.throwOnError = false + } + const throwOnError = query?.state.status === 'error' && typeof options.throwOnError === 'function' @@ -43,7 +44,7 @@ export const ensurePreventErrorBoundaryRetry = < ]) : options.throwOnError - if (options.suspense || throwOnError) { + if (suspense || throwOnError) { // Prevent retrying failed query if the error boundary has not been reset yet if (!errorResetBoundary.isReset()) { options.retryOnMount = false @@ -87,7 +88,7 @@ export const getHasError = < }: { result: QueryObserverResult errorResetBoundary: QueryErrorResetBoundaryValue - throwOnError: ThrowOnError + throwOnError?: ThrowOnError query: Query | undefined suspense: boolean | undefined }) => { diff --git a/packages/preact-query/src/index.ts b/packages/preact-query/src/index.ts index 71b4b1f9366..5805a661d49 100644 --- a/packages/preact-query/src/index.ts +++ b/packages/preact-query/src/index.ts @@ -3,6 +3,9 @@ // Re-export core // oxlint-disable-next-line tanstack-query/no-restricted-syntax export * from '@tanstack/query-core' +export { QueryClient } from './QueryClient' +export type { DefaultOptions, QueryClientConfig } from './QueryClient' +export type { ThrowOnError } from './types' // Preact Query export type { diff --git a/packages/preact-query/src/suspense.ts b/packages/preact-query/src/suspense.ts index c31e23d0ba9..83ee038f5d7 100644 --- a/packages/preact-query/src/suspense.ts +++ b/packages/preact-query/src/suspense.ts @@ -38,47 +38,32 @@ export const defaultThrowOnError = < * collected. A `'static'` `staleTime` is kept as is. Mutates the options. * @param defaultedOptions - The defaulted query options to adjust. */ -export const ensureSuspenseTimers = ( +export const prepareSuspenseOptions = ( defaultedOptions: DefaultedQueryObserverOptions, ) => { - if (defaultedOptions.suspense) { - // Handle staleTime to ensure minimum 1000ms in Suspense mode - // This prevents unnecessary refetching when components remount after suspending - const MIN_SUSPENSE_TIME_MS = 1000 - - const clamp = (value: number | 'static' | undefined) => - value === 'static' - ? value - : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) - - const originalStaleTime = defaultedOptions.staleTime - defaultedOptions.staleTime = - typeof originalStaleTime === 'function' - ? (...args) => clamp(originalStaleTime(...args)) - : clamp(originalStaleTime) - - if (typeof defaultedOptions.gcTime === 'number') { - defaultedOptions.gcTime = Math.max( - defaultedOptions.gcTime, - MIN_SUSPENSE_TIME_MS, - ) - } + // Handle staleTime to ensure minimum 1000ms in Suspense mode + // This prevents unnecessary refetching when components remount after suspending + const MIN_SUSPENSE_TIME_MS = 1000 + + const clamp = (value: number | 'static' | undefined) => + value === 'static' + ? value + : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) + + const originalStaleTime = defaultedOptions.staleTime + defaultedOptions.staleTime = + typeof originalStaleTime === 'function' + ? (...args) => clamp(originalStaleTime(...args)) + : clamp(originalStaleTime) + + if (typeof defaultedOptions.gcTime === 'number') { + defaultedOptions.gcTime = Math.max( + defaultedOptions.gcTime, + MIN_SUSPENSE_TIME_MS, + ) } } -/** - * Checks whether a query should suspend: `suspense` is enabled and the result is still `pending`. - * @param defaultedOptions - The defaulted query options, if any. - * @param result - The current result of the observer. - * @returns `true` if the component should suspend. - */ -export const shouldSuspend = ( - defaultedOptions: - | DefaultedQueryObserverOptions - | undefined, - result: QueryObserverResult, -) => defaultedOptions?.suspense && result.isPending - const shouldFetchInBackground = (result: QueryObserverResult) => result.isFetching && result.isPlaceholderData @@ -138,10 +123,8 @@ const useReadSuspenseQuery = ( client: QueryClient, errorResetBoundary: QueryErrorResetBoundaryValue, ) => { - if (!defaultedOptions.suspense) return - const result = reader.getSnapshot() - const suspend = shouldSuspend(defaultedOptions, result) + const suspend = result.isPending if (!suspend && !shouldFetchInBackground(result)) return const query = client.getQueryCache().build(client, defaultedOptions) @@ -154,9 +137,13 @@ const useReadSuspenseQuery = ( if (suspend) use(promise) } +const canFetchOnQueryChange = (query: Query) => + query.state.status !== 'error' + /** Supplies Suspense behavior for one query. */ export const suspenseQueryPolicy = { - prepare: ensureSuspenseTimers, + prepare: prepareSuspenseOptions, + canFetchOnQueryChange, readQuery: useReadSuspenseQuery, } @@ -168,9 +155,9 @@ const useReadSuspenseQueries = ( ) => { const suspensePromises = reader.getSnapshot().flatMap((result, index) => { const options = defaultedQueries[index] - if (!options?.suspense) return [] + if (!options) return [] - const suspend = shouldSuspend(options, result) + const suspend = result.isPending if (!suspend && !shouldFetchInBackground(result)) return [] const observer = new QueryObserver(client, options) @@ -191,6 +178,9 @@ const useReadSuspenseQueries = ( /** Supplies Suspense behavior for parallel queries. */ export const suspenseQueriesPolicy = { - prepare: ensureSuspenseTimers, + prepare: prepareSuspenseOptions, + canFetchOnQueryChange, readQueries: useReadSuspenseQueries, + canCombine: (results: Array) => + results.every((result) => result.data !== undefined), } diff --git a/packages/preact-query/src/types.ts b/packages/preact-query/src/types.ts index 2c12ae34fbc..67a283b8bf0 100644 --- a/packages/preact-query/src/types.ts +++ b/packages/preact-query/src/types.ts @@ -1,6 +1,7 @@ /* istanbul ignore file */ import type { DefaultError, + DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, DistributiveOmit, @@ -14,6 +15,7 @@ import type { MutationObserverResult, OmitKeyof, Override, + Query, QueryExecuteOptions, QueryKey, QueryObserverOptions, @@ -22,6 +24,50 @@ import type { SkipToken, } from '@tanstack/query-core' +/** A boolean or predicate that sends query errors to the nearest error boundary. */ +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) + +interface QueryErrorOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> { + /** + * Set to `true` to throw query errors to the nearest error boundary. + * A predicate receives the error and query and decides whether to throw. + * This option is ignored when `notifyOnChangeProps` is `'none'`. + * @defaultValue false + */ + throwOnError?: ThrowOnError +} + +/** @internal */ +export type DefaultedQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> & + QueryErrorOptions + /** * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't * relevant, e.g. when accepting options for any query in a helper function. @@ -50,13 +96,10 @@ export interface UseBaseQueryOptions< TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> extends QueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> { +> + extends + QueryObserverOptions, + QueryErrorOptions { /** * Set this to `false` to unsubscribe this observer from updates to the query cache. * @defaultValue true @@ -148,8 +191,7 @@ export type UsePrefetchInfiniteQueryOptions< */ export type AnyUseQueryOptions = UseQueryOptions /** - * The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which - * `preact-query` derives from which hook you call rather than exposing as an option). + * The options accepted by `useQuery`. Uses the options from {@link UseBaseQueryOptions}. * @template TQueryFnData - The type your `queryFn` resolves to. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no @@ -161,9 +203,12 @@ export interface UseQueryOptions< TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> extends OmitKeyof< - UseBaseQueryOptions, - 'suspense' +> extends UseBaseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryFnData, + TQueryKey > {} /** @@ -217,8 +262,7 @@ export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions< > /** * The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} from - * `@tanstack/query-core` with the `preact-query`-specific `subscribed` option, minus `suspense` (which - * `preact-query` derives from which hook you call rather than exposing as an option). + * `@tanstack/query-core` with `subscribed` and `throwOnError`. * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, @@ -232,16 +276,21 @@ export interface UseInfiniteQueryOptions< TData = InfiniteData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> extends OmitKeyof< - InfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - 'suspense' -> { +> + extends + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + QueryErrorOptions< + TQueryFnData, + TError, + InfiniteData, + TQueryKey + > { /** * Set this to `false` to unsubscribe this observer from updates to the query cache. * @defaultValue true @@ -370,7 +419,7 @@ export type UseSuspenseInfiniteQueryResult< export type AnyUseMutationOptions = UseMutationOptions /** * The options accepted by `useMutation`. Same as {@link MutationObserverOptions} from `@tanstack/query-core`, - * minus the internal `_defaulted` flag. + * with `throwOnError` and without the internal `_defaulted` flag. * @template TData - The type your mutation function resolves to. * @template TError - The type of errors your mutation function may throw. * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. @@ -385,7 +434,14 @@ export interface UseMutationOptions< > extends OmitKeyof< MutationObserverOptions, '_defaulted' -> {} +> { + /** + * Set to `true` to throw mutation errors to the nearest error boundary. + * A predicate receives the error and decides whether to throw. + * @defaultValue false + */ + throwOnError?: boolean | ((error: TError) => boolean) +} /** * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call diff --git a/packages/preact-query/src/useBaseQuery.ts b/packages/preact-query/src/useBaseQuery.ts index 0e22aaf91af..1e36b5dc8cf 100644 --- a/packages/preact-query/src/useBaseQuery.ts +++ b/packages/preact-query/src/useBaseQuery.ts @@ -4,8 +4,8 @@ import { useIsRestoring } from './IsRestoringProvider' import { useQueryClient } from './QueryClientProvider' import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' import { - ensurePreventErrorBoundaryRetry, getHasError, + prepareErrorBoundaryOptions, useClearResetErrorBoundary, } from './errorBoundaryUtils' import { useSyncExternalStore } from './utils' @@ -16,7 +16,7 @@ import type { QueryObserverResult, } from '@tanstack/query-core' import type { suspenseQueryPolicy } from './suspense' -import type { UseBaseQueryOptions } from './types' +import type { DefaultedQueryOptions, UseBaseQueryOptions } from './types' /** * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and @@ -61,10 +61,13 @@ export function useBaseQuery< const isRestoring = useIsRestoring() const errorResetBoundary = useQueryErrorResetBoundary() const client = useQueryClient(queryClient) - const defaultedOptions = client.defaultQueryOptions({ - ...options, - suspense: !!suspense, - }) + const defaultedOptions: DefaultedQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > = client.defaultQueryOptions({ ...options }) const query = client .getQueryCache() @@ -90,7 +93,12 @@ export function useBaseQuery< : undefined suspense?.prepare(defaultedOptions) - ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions( + defaultedOptions, + errorResetBoundary, + query, + !!suspense, + ) useClearResetErrorBoundary(errorResetBoundary) @@ -102,7 +110,10 @@ export function useBaseQuery< ), ) - const reader = observer.createResultReader(defaultedOptions) + const reader = observer.createResultReader( + defaultedOptions, + suspense?.canFetchOnQueryChange, + ) suspense?.readQuery( defaultedOptions, @@ -142,7 +153,7 @@ export function useBaseQuery< errorResetBoundary, throwOnError: defaultedOptions.throwOnError, query, - suspense: defaultedOptions.suspense, + suspense: !!suspense, }) ) { throw result.error diff --git a/packages/preact-query/src/useMutation.ts b/packages/preact-query/src/useMutation.ts index 9547d93c8ea..726471c2fa6 100644 --- a/packages/preact-query/src/useMutation.ts +++ b/packages/preact-query/src/useMutation.ts @@ -1,12 +1,7 @@ -import { - MutationObserver, - noop, - notifyManager, - shouldThrowError, -} from '@tanstack/query-core' +import { MutationObserver, noop, notifyManager } from '@tanstack/query-core' import { useCallback, useEffect, useState } from 'preact/hooks' import { useQueryClient } from './QueryClientProvider' -import { useSyncExternalStore } from './utils' +import { shouldThrowError, useSyncExternalStore } from './utils' import type { DefaultError, QueryClient } from '@tanstack/query-core' import type { UseMutateFunction, @@ -229,9 +224,15 @@ export function useMutation< [observer], ) + const observerOptions: UseMutationOptions< + TData, + TError, + TVariables, + TOnMutateResult + > = observer.options if ( result.error && - shouldThrowError(observer.options.throwOnError, [result.error]) + shouldThrowError(observerOptions.throwOnError, [result.error]) ) { throw result.error } diff --git a/packages/preact-query/src/useQueries.ts b/packages/preact-query/src/useQueries.ts index 746d0ca79c5..0f57fbbebc7 100644 --- a/packages/preact-query/src/useQueries.ts +++ b/packages/preact-query/src/useQueries.ts @@ -4,8 +4,8 @@ import { useIsRestoring } from './IsRestoringProvider' import { useQueryClient } from './QueryClientProvider' import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' import { - ensurePreventErrorBoundaryRetry, getHasError, + prepareErrorBoundaryOptions, useClearResetErrorBoundary, } from './errorBoundaryUtils' import { useSyncExternalStore } from './utils' @@ -17,12 +17,13 @@ import type { QueryClient, QueryFunction, QueryKey, - QueryObserverOptions, - ThrowOnError, + QueryObserverResult, } from '@tanstack/query-core' import type { suspenseQueriesPolicy } from './suspense' import type { + DefaultedQueryOptions, DefinedUseQueryResult, + ThrowOnError, UseQueryOptions, UseQueryResult, } from './types' @@ -348,10 +349,8 @@ export function useBaseQueries< const defaultedQueries = useMemo( () => queries.map((opts) => { - const defaultedOptions = client.defaultQueryOptions({ - ...opts, - suspense: !!suspense, - } as QueryObserverOptions) + const defaultedOptions: DefaultedQueryOptions = + client.defaultQueryOptions({ ...opts }) // Make sure the results are already in fetching state before subscribing or updating options defaultedOptions._optimisticResults = isRestoring @@ -360,31 +359,59 @@ export function useBaseQueries< ? 'optimistic' : undefined + suspense?.prepare(defaultedOptions) return defaultedOptions }), [queries, client, isRestoring, subscribed, suspense], ) defaultedQueries.forEach((queryOptions) => { - suspense?.prepare(queryOptions) const query = client.getQueryCache().get(queryOptions.queryHash) - ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions( + queryOptions, + errorResetBoundary, + query, + !!suspense, + ) }) useClearResetErrorBoundary(errorResetBoundary) + const observerOptions = options as QueriesObserverOptions + const [observer] = useState( () => new QueriesObserver( client, defaultedQueries, - options as QueriesObserverOptions, + observerOptions, ), ) + const findErrorResult = (results: Array) => + results.find((result, index) => { + const query = defaultedQueries[index] + return ( + result.isError && + query && + getHasError({ + result, + errorResetBoundary, + throwOnError: query.throwOnError, + query: client.getQueryCache().get(query.queryHash), + suspense: !!suspense, + }) + ) + }) + const reader = observer.createResultReader( defaultedQueries, - options as QueriesObserverOptions, + observerOptions, + { + canFetchOnQueryChange: suspense?.canFetchOnQueryChange, + canCombine: (results) => + suspense?.canCombine(results) !== false && !findErrorResult(results), + }, ) suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) @@ -412,20 +439,7 @@ export function useBaseQueries< reader.getSnapshot, ) - const firstErrorResult = results.find((result, index) => { - const query = defaultedQueries[index] - return ( - query && - getHasError({ - result, - errorResetBoundary, - throwOnError: query.throwOnError, - query: client.getQueryCache().get(query.queryHash), - suspense: query.suspense, - }) - ) - }) - + const firstErrorResult = findErrorResult(results) if (firstErrorResult) { throw firstErrorResult.error } diff --git a/packages/preact-query/src/useSuspenseQueries.ts b/packages/preact-query/src/useSuspenseQueries.ts index 3b1008bead6..4dfb6593b96 100644 --- a/packages/preact-query/src/useSuspenseQueries.ts +++ b/packages/preact-query/src/useSuspenseQueries.ts @@ -8,9 +8,12 @@ import type { QueryClient, QueryFunction, QueryKey, - ThrowOnError, } from '@tanstack/query-core' -import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' +import type { + ThrowOnError, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' // `placeholderData` functions in useQueries never receive previous query data. type UseSuspenseQueryOptionsForUseSuspenseQueries< diff --git a/packages/preact-query/src/utils.ts b/packages/preact-query/src/utils.ts index d107969134a..83596b1dbca 100644 --- a/packages/preact-query/src/utils.ts +++ b/packages/preact-query/src/utils.ts @@ -107,3 +107,20 @@ export function useSyncExternalStoreWithSelector( return useSyncExternalStore(subscribe, getSelectedSnapshot) } + +/** + * Resolves the adapter's error boundary option. + * @param throwOnError - A boolean or a predicate. + * @param params - The arguments passed to the predicate. + * @returns Whether to throw the error. + */ +export function shouldThrowError) => boolean>( + throwOnError: boolean | T | undefined, + params: Parameters, +): boolean { + if (typeof throwOnError === 'function') { + return throwOnError(...params) + } + + return !!throwOnError +} diff --git a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx index 4deb4606da7..9b44e47793c 100644 --- a/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx +++ b/packages/query-core/src/__tests__/infiniteQueryObserver.test.tsx @@ -224,7 +224,6 @@ describe('InfiniteQueryObserver', () => { queryFn: () => sleep(10).then(() => 1), initialPageParam: 1, getNextPageParam: () => 2, - throwOnError: true, refetchOnReconnect: false, queryHash: key.join(''), } diff --git a/packages/query-core/src/__tests__/mutationObserver.test-d.tsx b/packages/query-core/src/__tests__/mutationObserver.test-d.tsx index f19efded4eb..5c7e7ac4870 100644 --- a/packages/query-core/src/__tests__/mutationObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/mutationObserver.test-d.tsx @@ -231,16 +231,6 @@ describe('mutationObserver', () => { }) }) - describe('throwOnError', () => { - it('should be a boolean or a predicate taking the error', () => { - expectTypeOf< - MutationObserverOptions['throwOnError'] - >().toEqualTypeOf< - boolean | ((error: CustomError) => boolean) | undefined - >() - }) - }) - describe('meta', () => { it('should be optional mutation meta', () => { expectTypeOf< diff --git a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx index 0cb59c59e08..43e13f7d488 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test-d.tsx @@ -49,7 +49,9 @@ describe('queriesObserver', () => { describe('combine', () => { it('should be optional', () => { - expectTypeOf>().toEqualTypeOf<{ + expectTypeOf< + Pick, 'combine'> + >().toEqualTypeOf<{ combine?: (result: Array) => number }>() }) @@ -94,7 +96,7 @@ describe('queriesObserver', () => { it('should reject an option it does not declare', () => { new QueriesObserver(queryClient, [], { - // @ts-expect-error combine is the only option + // @ts-expect-error select is not a queries observer option select: (results: Array) => results, }) diff --git a/packages/query-core/src/__tests__/queriesObserver.test.tsx b/packages/query-core/src/__tests__/queriesObserver.test.tsx index db926c7e274..cc7b36ef6e7 100644 --- a/packages/query-core/src/__tests__/queriesObserver.test.tsx +++ b/packages/query-core/src/__tests__/queriesObserver.test.tsx @@ -738,7 +738,7 @@ describe('queriesObserver', () => { expect(newCombined.count).toBe(2) }) - it('should skip combine notifications while suspense queries have no data', () => { + it('preserves the last combined value while notifying subscribers about missing data', async () => { const key = createKey() const combine = vi.fn< (results: Array) => Array @@ -749,7 +749,6 @@ describe('queriesObserver', () => { queryKey: key, queryFn: () => sleep(10).then(() => 'data'), staleTime: Infinity, - suspense: true, } queryClient.setQueryData(key, 'data') @@ -758,23 +757,40 @@ describe('queriesObserver', () => { combine, }) - const combinedResultReader = observer.createResultReader([query], { - combine, - }) + const combinedResultReader = observer.createResultReader( + [query], + { combine }, + { + canCombine: (results) => + results.every((result) => result.data !== undefined), + }, + ) const rawResult = combinedResultReader.getSnapshot() const getCombinedResult = combinedResultReader.combineResult - expect(getCombinedResult(rawResult)).toStrictEqual(['data']) + const initialCombined = getCombinedResult(rawResult) + expect(initialCombined).toStrictEqual(['data']) + combinedResultReader.commit() expect(combine).toHaveBeenCalledTimes(1) - const unsubscribe = observer.subscribe(() => undefined) + const listener = vi.fn<(results: Array) => void>() + const unsubscribe = observer.subscribe(listener) - void queryClient.resetQueries({ queryKey: key }) + const reset = queryClient.resetQueries({ queryKey: key }) + expect(listener).toHaveBeenLastCalledWith([ + expect.objectContaining({ data: undefined }), + ]) expect(combine).toHaveBeenCalledTimes(1) + await vi.advanceTimersByTimeAsync(10) + await reset + expect(getCombinedResult(combinedResultReader.getSnapshot())).toBe( + initialCombined, + ) + unsubscribe() }) - it('should skip combine notifications after suspense is enabled without structural changes', () => { + it('should skip combine notifications after combine readiness is enabled without structural changes', () => { const key = createKey() const combine = vi.fn< (results: Array) => Array @@ -785,7 +801,6 @@ describe('queriesObserver', () => { queryKey: key, queryFn: () => sleep(10).then(() => 'data'), staleTime: Infinity, - suspense: false, } queryClient.setQueryData(key, 'data') @@ -804,15 +819,16 @@ describe('queriesObserver', () => { const unsubscribe = observer.subscribe(() => undefined) - observer.setQueries( - [ + observer + .createResultReader( + [query], + { combine }, { - ...query, - suspense: true, + canCombine: (results) => + results.every((result) => result.data !== undefined), }, - ], - { combine }, - ) + ) + .commit() void queryClient.resetQueries({ queryKey: key }) expect(combine).toHaveBeenCalledTimes(1) @@ -820,196 +836,36 @@ describe('queriesObserver', () => { unsubscribe() }) - it('should notify listeners when a query with throwOnError fails without changing the combined result', async () => { - const key = createKey() - const combine = (results: Array) => - results.map((result) => result.data) - const query = { - queryKey: key, - queryFn: () => sleep(10).then(() => Promise.reject(new Error('error'))), - retry: false, - throwOnError: true, - } - - const observer = new QueriesObserver>(queryClient, [query]) - observer.setQueries([query], { combine }) - - const reader = observer.createResultReader([query], { combine }) - expect(reader.combineResult(reader.getSnapshot())).toStrictEqual([ - undefined, - ]) - reader.commit() - - const results: Array> = [] - const unsubscribe = observer.subscribe((result) => { - results.push(result) - }) - - await vi.advanceTimersByTimeAsync(10) - expect(results).toHaveLength(1) - expect(results[0]?.[0]).toMatchObject({ - status: 'error', - error: new Error('error'), - }) - - unsubscribe() - }) - - it('should not notify listeners when a query without throwOnError fails without changing the combined result', async () => { - const key = createKey() - const combine = (results: Array) => - results.map((result) => result.data) - const query = { - queryKey: key, - queryFn: () => sleep(10).then(() => Promise.reject(new Error('error'))), - retry: false, - } - - const observer = new QueriesObserver>(queryClient, [query]) - observer.setQueries([query], { combine }) - - const reader = observer.createResultReader([query], { combine }) - expect(reader.combineResult(reader.getSnapshot())).toStrictEqual([ - undefined, - ]) - reader.commit() - - const listener = vi.fn<(result: Array) => void>() - const unsubscribe = observer.subscribe(listener) - - await vi.advanceTimersByTimeAsync(10) - expect(listener).not.toHaveBeenCalled() - - unsubscribe() - }) - - it('should notify listeners when a query with throwOnError function returning true fails without changing the combined result', async () => { - const key = createKey() - const combine = (results: Array) => - results.map((result) => result.data) - const throwOnError = vi.fn<() => boolean>(() => true) - const query = { - queryKey: key, - queryFn: () => sleep(10).then(() => Promise.reject(new Error('error'))), - retry: false, - throwOnError, - } - - const observer = new QueriesObserver>(queryClient, [query]) - observer.setQueries([query], { combine }) - - const reader = observer.createResultReader([query], { combine }) - expect(reader.combineResult(reader.getSnapshot())).toStrictEqual([ - undefined, - ]) - reader.commit() - - const listener = vi.fn<(result: Array) => void>() - const unsubscribe = observer.subscribe(listener) - - await vi.advanceTimersByTimeAsync(10) - expect(listener).toHaveBeenCalledTimes(1) - expect(throwOnError).toHaveBeenCalledWith( - new Error('error'), - queryClient.getQueryCache().find({ queryKey: key }), - ) - - unsubscribe() - }) - - it('should not notify listeners when a query with throwOnError function returning false fails without changing the combined result', async () => { - const key = createKey() - const combine = (results: Array) => - results.map((result) => result.data) - const throwOnError = vi.fn<() => boolean>(() => false) - const query = { - queryKey: key, - queryFn: () => sleep(10).then(() => Promise.reject(new Error('error'))), - retry: false, - throwOnError, - } - - const observer = new QueriesObserver>(queryClient, [query]) - observer.setQueries([query], { combine }) - - const reader = observer.createResultReader([query], { combine }) - expect(reader.combineResult(reader.getSnapshot())).toStrictEqual([ - undefined, - ]) - reader.commit() - - const listener = vi.fn<(result: Array) => void>() - const unsubscribe = observer.subscribe(listener) - - await vi.advanceTimersByTimeAsync(10) - expect(listener).not.toHaveBeenCalled() - expect(throwOnError).toHaveBeenCalledWith( - new Error('error'), - queryClient.getQueryCache().find({ queryKey: key }), - ) - - unsubscribe() - }) - - it('should not notify listeners while a query with throwOnError refetches after failing without changing the combined result', async () => { - const key = createKey() - const combine = (results: Array) => - results.map((result) => result.data) - let count = 0 + it('keeps subscribers quiet when a selector fails and the combined value stays the same', () => { + const queryKey = createKey() + const error = new Error('select failed') + queryClient.setQueryData(queryKey, 'good') const query = { - queryKey: key, - queryFn: () => - sleep(10).then(() => - count++ === 0 ? 'data' : Promise.reject(new Error('error')), - ), - retry: false, - throwOnError: true, - notifyOnChangeProps: 'all' as const, - } - - const observer = new QueriesObserver>(queryClient, [query]) - observer.setQueries([query], { combine }) - + queryKey, + queryFn: defaultQueryFn, + enabled: false, + select: (data: string) => { + if (data === 'bad') { + throw error + } + return data + }, + } as const + const combine = (results: Array) => results[0]!.data + const observer = new QueriesObserver(queryClient, [query]) const reader = observer.createResultReader([query], { combine }) - expect(reader.combineResult(reader.getSnapshot())).toStrictEqual([ - undefined, - ]) + expect(reader.combineResult(reader.getSnapshot())).toBe('good') reader.commit() - - const listener = vi.fn<(result: Array) => void>() + const listener = vi.fn<() => void>() const unsubscribe = observer.subscribe(listener) - await vi.advanceTimersByTimeAsync(10) - expect(listener).toHaveBeenCalledTimes(1) - expect(listener).toHaveBeenLastCalledWith([ - expect.objectContaining({ status: 'success', data: 'data' }), - ]) - - void queryClient.refetchQueries({ queryKey: key }) - await vi.advanceTimersByTimeAsync(10) - expect(listener).toHaveBeenCalledTimes(2) - expect(listener).toHaveBeenLastCalledWith([ - expect.objectContaining({ - status: 'error', - fetchStatus: 'idle', - data: 'data', - }), - ]) + queryClient.setQueryData(queryKey, 'bad') - void queryClient.refetchQueries({ queryKey: key }) - await vi.advanceTimersByTimeAsync(0) expect(observer.getCurrentResult()[0]).toMatchObject({ - status: 'error', - fetchStatus: 'fetching', + data: 'good', + error, }) - expect(listener).toHaveBeenCalledTimes(2) - - await vi.advanceTimersByTimeAsync(10) - expect(listener).toHaveBeenCalledTimes(3) - expect(listener).toHaveBeenLastCalledWith([ - expect.objectContaining({ status: 'error', fetchStatus: 'idle' }), - ]) - + expect(listener).not.toHaveBeenCalled() unsubscribe() }) diff --git a/packages/query-core/src/__tests__/queryClient.test.tsx b/packages/query-core/src/__tests__/queryClient.test.tsx index 08f56f1eb9c..56aa40e515d 100644 --- a/packages/query-core/src/__tests__/queryClient.test.tsx +++ b/packages/query-core/src/__tests__/queryClient.test.tsx @@ -200,14 +200,14 @@ describe('queryClient', () => { it('should merge defaultOptions', () => { const key = createKey() - queryClient.setQueryDefaults([...key, 'todo'], { suspense: true }) + queryClient.setQueryDefaults([...key, 'todo'], { retry: false }) queryClient.setQueryDefaults([...key, 'todo', 'detail'], { staleTime: 5000, }) expect( queryClient.getQueryDefaults([...key, 'todo', 'detail']), - ).toMatchObject({ suspense: true, staleTime: 5000 }) + ).toMatchObject({ retry: false, staleTime: 5000 }) }) }) diff --git a/packages/query-core/src/__tests__/queryObserver.test-d.tsx b/packages/query-core/src/__tests__/queryObserver.test-d.tsx index 8049ce4ce16..871755e9a3e 100644 --- a/packages/query-core/src/__tests__/queryObserver.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test-d.tsx @@ -345,44 +345,6 @@ describe('queryObserver', () => { }) }) - describe('throwOnError', () => { - it('should type the error given to a throwOnError callback', () => { - new QueryObserver<{ value: string }, CustomError>(queryClient, { - queryKey: createKey(), - queryFn: () => Promise.resolve({ value: 'data' }), - throwOnError: (error, query) => { - expectTypeOf(error).toEqualTypeOf() - expectTypeOf(query.state.data).toEqualTypeOf< - { value: string } | undefined - >() - return false - }, - }) - }) - - it('should only accept a boolean from a throwOnError callback', () => { - new QueryObserver(queryClient, { - queryKey: createKey(), - queryFn: () => Promise.resolve('data'), - // @ts-expect-error the callback must return a boolean - throwOnError: () => 'yes', - }) - - expectTypeOf< - Extract< - QueryObserverOptions['throwOnError'], - (...args: Array) => any - > - >().returns.toEqualTypeOf() - expectTypeOf< - Exclude< - QueryObserverOptions['throwOnError'], - (...args: Array) => any - > - >().toEqualTypeOf() - }) - }) - describe('retry', () => { it('should type the error given to a retry callback', () => { new QueryObserver(queryClient, { @@ -684,14 +646,6 @@ describe('queryObserver', () => { }) }) - describe('suspense', () => { - it('should type suspense as a boolean', () => { - expectTypeOf().toEqualTypeOf< - boolean | undefined - >() - }) - }) - describe('refetchIntervalInBackground', () => { it('should type refetchIntervalInBackground as a boolean', () => { expectTypeOf< @@ -1465,14 +1419,6 @@ describe('queryObserver', () => { }, ) - expectTypeOf< - Extract< - typeof observer.options.throwOnError, - (...args: Array) => any - > - >() - .parameter(0) - .toEqualTypeOf() expectTypeOf(observer.options.select).toEqualTypeOf< ((data: { value: string }) => { value: string }) | undefined >() diff --git a/packages/query-core/src/__tests__/queryObserver.test.tsx b/packages/query-core/src/__tests__/queryObserver.test.tsx index 2276485a60d..97697279277 100644 --- a/packages/query-core/src/__tests__/queryObserver.test.tsx +++ b/packages/query-core/src/__tests__/queryObserver.test.tsx @@ -1013,13 +1013,15 @@ describe('queryObserver', () => { unsubscribe() }) - it('notifies listeners of errors with notifyOnChangeProps set to none and throwOnError enabled', async () => { + it('suppresses notifications when an error appears or clears with notifyOnChangeProps set to none', async () => { const error = new Error('fetch failed') const observer = new QueryObserver(queryClient, { queryKey: createKey(), - queryFn: () => Promise.reject(error), + queryFn: vi + .fn<() => Promise>() + .mockRejectedValueOnce(error) + .mockResolvedValueOnce('data'), notifyOnChangeProps: 'none', - throwOnError: true, retry: false, }) const listener = vi.fn<(result: QueryObserverResult) => void>() @@ -1027,9 +1029,13 @@ describe('queryObserver', () => { await vi.advanceTimersByTimeAsync(0) - expect(listener).toHaveBeenCalledExactlyOnceWith( - expect.objectContaining({ error }), - ) + expect(observer.getCurrentResult().error).toBe(error) + expect(listener).not.toHaveBeenCalled() + + await observer.refetch() + + expect(observer.getCurrentResult().error).toBeNull() + expect(listener).not.toHaveBeenCalled() unsubscribe() }) @@ -1724,27 +1730,25 @@ describe('queryObserver', () => { expect(queryClient.getQueryState(key)?.fetchStatus).toBe('idle') }) - it('should track error prop when throwOnError is true', async () => { + it('notifies listeners of errors when only data is tracked', async () => { const key = createKey() const results: Array = [] const observer = new QueryObserver(queryClient, { queryKey: key, queryFn: () => Promise.reject('error'), retry: false, - throwOnError: true, }) const trackedResult = observer.trackResult( observer.getCurrentResult(), (prop) => { - if (prop === 'data' || prop === 'status') { + if (prop === 'data') { observer.trackProp(prop) } }, ) trackedResult.data - trackedResult.status const unsubscribe = observer.subscribe((result) => { results.push(result) @@ -1762,39 +1766,6 @@ describe('queryObserver', () => { unsubscribe() }) - it('should not track error prop when throwOnError is not set', async () => { - const key = createKey() - const results: Array = [] - const observer = new QueryObserver(queryClient, { - queryKey: key, - queryFn: () => Promise.reject('error'), - retry: false, - }) - - const trackedResult = observer.trackResult( - observer.getCurrentResult(), - (prop) => { - if (prop === 'data') { - observer.trackProp(prop) - } - }, - ) - - trackedResult.data - - const unsubscribe = observer.subscribe((result) => { - results.push(result) - }) - await vi.advanceTimersByTimeAsync(0) - - // Without throwOnError, `error` is not auto-added to trackedProps. - // Since only `data` is tracked and it did not change (stayed undefined), - // the listener is not invoked even though `error` prop changed. - expect(results).toHaveLength(0) - - unsubscribe() - }) - it('should not refetch on mount when retryOnMount is false and query is in error state', async () => { const key = createKey() const queryFn = vi.fn<() => Promise>(() => Promise.reject('error')) diff --git a/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx b/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx index 03a5a85fe1e..74cb353b60d 100644 --- a/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx +++ b/packages/query-core/src/__tests__/queryObserverResultReader.test-d.tsx @@ -50,7 +50,6 @@ describe('result reader types', () => { initialPageParam: 0, getNextPageParam: (last) => last + 1, queryHash: 'value', - throwOnError: false, refetchOnReconnect: true, } const observer = new InfiniteQueryObserver(new QueryClient(), options) diff --git a/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx b/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx index b87d8233c2b..f496a270fcf 100644 --- a/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx +++ b/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx @@ -125,6 +125,40 @@ describe('query observer result readers', () => { unsubscribe() }) + it('honors the fetch policy when reading and committing a switch to a failed query', async () => { + const error = new Error('fetch failed') + const queryFn = vi.fn<() => Promise>().mockRejectedValue(error) + const failedOptions = client.defaultQueryOptions({ + queryKey: createKey(), + queryFn, + retry: false, + _optimisticResults: 'optimistic', + }) + await expect(client.query(failedOptions)).rejects.toBe(error) + + const observer = new QueryObserver(client, { + queryKey: createKey(), + queryFn, + initialData: 'data', + staleTime: Infinity, + }) + const unsubscribe = observer.subscribe(vi.fn<() => void>()) + const reader = observer.createResultReader( + failedOptions, + (query) => query.state.status !== 'error', + ) + + expect(reader.getSnapshot()).toMatchObject({ error, fetchStatus: 'idle' }) + reader.commit() + expect(observer.getCurrentResult()).toMatchObject({ + error, + fetchStatus: 'idle', + }) + expect(queryFn).toHaveBeenCalledTimes(1) + + unsubscribe() + }) + it('exposes retry failures, terminal errors, and recovery', async () => { const error = new Error('fetch failed') let attempts = 0 @@ -408,7 +442,6 @@ describe('query observer result readers', () => { > = { queryKey: key, queryHash: JSON.stringify(key), - throwOnError: false, refetchOnReconnect: true, queryFn: ({ pageParam }) => sleep(10).then(() => pageParam), _optimisticResults: 'optimistic' as const, diff --git a/packages/query-core/src/__tests__/utils.test-d.tsx b/packages/query-core/src/__tests__/utils.test-d.tsx index ccc66b4214c..276d5d94305 100644 --- a/packages/query-core/src/__tests__/utils.test-d.tsx +++ b/packages/query-core/src/__tests__/utils.test-d.tsx @@ -19,7 +19,6 @@ import { replaceEqualDeep, resolveQueryValue, shallowEqualObjects, - shouldThrowError, skipToken, timeUntilStale, } from '../utils' @@ -777,46 +776,6 @@ describe('ensureQueryFn', () => { }) }) -describe('shouldThrowError', () => { - it('should tie params to the parameters of the throwOnError function', () => { - type ThrowOnError = (error: CustomError, query: Query) => boolean - - expectTypeOf(shouldThrowError) - .parameter(1) - .toEqualTypeOf<[error: CustomError, query: Query]>() - - expectTypeOf( - shouldThrowError, - ).returns.toEqualTypeOf() - }) - - it('should constrain the throwOnError function to one returning a boolean', () => { - expectTypeOf( - shouldThrowError<(error: CustomError) => boolean>( - (_error) => true, - [new CustomError()], - ), - ).toEqualTypeOf() - - shouldThrowError< - // @ts-expect-error a throwOnError function has to return a boolean - (error: CustomError) => unknown - >((_error) => undefined, [new CustomError()]) - }) - - it('should accept a boolean or undefined as throwOnError', () => { - type ThrowOnError = (error: CustomError) => boolean - - expectTypeOf(shouldThrowError) - .parameter(0) - .toEqualTypeOf() - - expectTypeOf( - shouldThrowError(true, [new CustomError()]), - ).toEqualTypeOf() - }) -}) - describe('addConsumeAwareSignal', () => { it('should intersect the object with a signal property', () => { const result = addConsumeAwareSignal( diff --git a/packages/query-core/src/__tests__/utils.test.tsx b/packages/query-core/src/__tests__/utils.test.tsx index 1fa46835e7d..20e7ce9fba5 100644 --- a/packages/query-core/src/__tests__/utils.test.tsx +++ b/packages/query-core/src/__tests__/utils.test.tsx @@ -16,7 +16,6 @@ import { partialMatchKey, replaceEqualDeep, shallowEqualObjects, - shouldThrowError, skipToken, } from '../utils' import type { QueryFunctionContext } from '..' @@ -761,24 +760,6 @@ describe('core/utils', () => { }) }) - describe('shouldThrowError', () => { - it('should return the result of executing throwOnError if throwOnError parameter is a function', () => { - const throwOnError = (error: Error) => error.message === 'test error' - expect(shouldThrowError(throwOnError, [new Error('test error')])).toBe( - true, - ) - expect(shouldThrowError(throwOnError, [new Error('other error')])).toBe( - false, - ) - }) - - it('should return throwOnError parameter itself if throwOnError is not a function', () => { - expect(shouldThrowError(true, [new Error('test error')])).toBe(true) - expect(shouldThrowError(false, [new Error('test error')])).toBe(false) - expect(shouldThrowError(undefined, [new Error('test error')])).toBe(false) - }) - }) - describe('addConsumeAwareSignal', () => { it('should allow page parameters to be passed to URLSearchParams', () => { const controller = new AbortController() diff --git a/packages/query-core/src/index.ts b/packages/query-core/src/index.ts index 0b313930aa5..455232191a2 100644 --- a/packages/query-core/src/index.ts +++ b/packages/query-core/src/index.ts @@ -39,7 +39,6 @@ export { noop, partialMatchKey, replaceEqualDeep, - shouldThrowError, defaultQueryFn, skipToken, } from './utils' @@ -105,7 +104,6 @@ export type { QueryOptions, InitialPageParam, InfiniteQueryPageParamsOptions, - ThrowOnError, QueryObserverOptions, WithRequired, DefaultedQueryObserverOptions, diff --git a/packages/query-core/src/infiniteQueryObserver.ts b/packages/query-core/src/infiniteQueryObserver.ts index b662821e5ab..f5dfb222ccd 100644 --- a/packages/query-core/src/infiniteQueryObserver.ts +++ b/packages/query-core/src/infiniteQueryObserver.ts @@ -3,6 +3,7 @@ import { QueryObserver } from './queryObserver' import type { Query } from './query' import type { QueryClient } from './queryClient' import type { + CanFetchOnQueryChange, QueryObserverResultContext, QueryObserverResultReader, } from './queryObserver' @@ -131,6 +132,7 @@ export class InfiniteQueryObserver< * belonging to an infinite query before delegating to the base * implementation. * @param options - The new infinite query observer options. + * @param canFetch - The fetch predicate for the options update. */ override setOptions( options: InfiniteObserverOptionsInput< @@ -140,14 +142,16 @@ export class InfiniteQueryObserver< TQueryKey, TPageParam >, + canFetch?: CanFetchOnQueryChange, ): void { options._type = 'infinite' - super.setOptions(options) + super.setOptions(options, canFetch) } /** * Creates a cached snapshot reader for an infinite query. * @param options - The defaulted options used to read and commit the query result. + * @param canFetch - The fetch predicate for this read and commit. * @returns A reader that keeps its result and computation state until commit. */ override createResultReader( @@ -158,11 +162,15 @@ export class InfiniteQueryObserver< TQueryKey, TPageParam >, + canFetch?: CanFetchOnQueryChange, ): QueryObserverResultReader> { - return super.createResultReader({ - ...options, - _type: 'infinite', - }) as QueryObserverResultReader> + return super.createResultReader( + { + ...options, + _type: 'infinite', + }, + canFetch, + ) as QueryObserverResultReader> } /** @@ -249,9 +257,16 @@ export class InfiniteQueryObserver< TQueryKey >, prevResult?: QueryObserverResult, + canFetch?: CanFetchOnQueryChange, ): InfiniteQueryObserverResult { const { state } = query - const parentResult = super.createResult(query, options, context, prevResult) + const parentResult = super.createResult( + query, + options, + context, + prevResult, + canFetch, + ) const { isFetching, isRefetching, isError, isRefetchError } = parentResult const fetchDirection = state.fetchMeta?.fetchMore?.direction diff --git a/packages/query-core/src/queriesObserver.ts b/packages/query-core/src/queriesObserver.ts index a1ea988b4f7..bff30dacc10 100644 --- a/packages/query-core/src/queriesObserver.ts +++ b/packages/query-core/src/queriesObserver.ts @@ -1,13 +1,10 @@ import { notifyManager } from './notifyManager' import { QueryObserver } from './queryObserver' import { Subscribable } from './subscribable' -import { - replaceEqualDeep, - shallowEqualObjects, - shouldThrowError, -} from './utils' +import { replaceEqualDeep, shallowEqualObjects } from './utils' import type { QueryClient } from './queryClient' import type { + CanFetchOnQueryChange, ObserverOptionsInput, QueryObserverResultReader, } from './queryObserver' @@ -82,6 +79,17 @@ export interface QueriesObserverOptions< combine?: CombineFn } +/** + * Controls automatic fetches and combining for a group of queries. + * @internal + */ +export interface QueriesObserverReaderPolicy { + /** Controls automatic fetches when switching or enabling a query. */ + canFetchOnQueryChange?: CanFetchOnQueryChange + /** Return false to notify with raw results and keep the last combined value. */ + canCombine?: (results: Array) => boolean +} + /** * A `QueriesObserver` watches an array of queries at once, exposing them as * a single array of `QueryObserverResult`s (or, when a `combine` option is @@ -111,6 +119,7 @@ export class QueriesObserver< #combineContext: CombineContext = {} #observerMatches: Array = [] #updatingQueries = false + #canCombine?: QueriesObserverReaderPolicy['canCombine'] constructor( client: QueryClient, @@ -175,8 +184,10 @@ export class QueriesObserver< #setQueries( newObserverMatches: Array, options?: QueriesObserverOptions, + canCombine?: QueriesObserverReaderPolicy['canCombine'], ): void { this.#options = options + this.#canCombine = canCombine if (process.env.NODE_ENV !== 'production') { const queryHashes = newObserverMatches.map( @@ -286,20 +297,26 @@ export class QueriesObserver< * their computation state. Abandoned readers do not change active observers. * @param queries - The options of the queries to read and commit. * @param options - The combine function used for this reader. + * @param policy - The fetch and combine policy for this read and commit. * @returns A reader with local snapshot and combine caches. */ createResultReader( queries: Array>, options?: QueriesObserverOptions, + policy?: QueriesObserverReaderPolicy, ): QueriesObserverResultReader { const matches = this.#findMatchingObservers(queries).map((match) => ({ ...match, - reader: match.observer.createResultReader(match.defaultedQueryOptions), + reader: match.observer.createResultReader( + match.defaultedQueryOptions, + policy?.canFetchOnQueryChange, + ), })) const queryHashes = matches.map( (match) => match.defaultedQueryOptions.queryHash, ) const combine = options?.combine + const canCombine = policy?.canCombine const context = { ...this.#combineContext } let result = this.#result @@ -333,7 +350,7 @@ export class QueriesObserver< }, commit: () => { this.#combineContext = { ...context } - this.#setQueries(matches, { combine }) + this.#setQueries(matches, { combine }, canCombine) if ( this.#options?.combine === combine && equalResults(this.#result, context.result) @@ -398,21 +415,7 @@ export class QueriesObserver< } #shouldSkipCombine(): boolean { - return ( - !this.#options?.combine || - this.#observers.some((observer, index) => { - const result = this.#result[index] - return ( - (observer.options.suspense && result?.data === undefined) || - (!!result?.isError && - !result.isFetching && - shouldThrowError(observer.options.throwOnError, [ - result.error, - observer.getCurrentQuery(), - ])) - ) - }) - ) + return !this.#options?.combine || this.#canCombine?.(this.#result) === false } #findMatchingObservers( diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 98b4771382c..16525473e2d 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -541,7 +541,7 @@ export class QueryClient { * The accepted options are `QueryObserverOptions` minus the fields that only make sense for a * reactive observer — `enabled`, `refetchInterval`, `refetchIntervalInBackground`, * `refetchOnWindowFocus`, `refetchOnReconnect`, `refetchOnMount`, `retryOnMount`, - * `notifyOnChangeProps`, `throwOnError`, `suspense`, and `placeholderData` are not part of this + * `notifyOnChangeProps` and `placeholderData` are not part of this * method's options. * Shared query options can contain `skipToken` as their `queryFn`. If the supplied options contain * the token, the call skips fetching and resolves with existing data regardless of freshness. @@ -1043,9 +1043,6 @@ export class QueryClient { defaultedOptions.refetchOnReconnect = defaultedOptions.networkMode !== 'always' } - if (defaultedOptions.throwOnError === undefined) { - defaultedOptions.throwOnError = !!defaultedOptions.suspense - } if (!defaultedOptions.networkMode && defaultedOptions.persister) { defaultedOptions.networkMode = 'offlineFirst' diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index 3ccdfb227d4..5573f38dd75 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -27,6 +27,14 @@ import type { RefetchOptions, } from './types' +/** + * Controls fetches caused by changes to the observed query. + * @internal + */ +export type CanFetchOnQueryChange = ( + query: Query, +) => boolean + type QueryObserverListener = ( result: QueryObserverResult, ) => void @@ -267,6 +275,7 @@ export class QueryObserver< * refetch-interval timers as needed. * @param options - The new observer options. They are defaulted with {@link * QueryClient#defaultQueryOptions} before being applied. + * @param canFetch - The fetch predicate for the options update. * @throws {Error} If `enabled` is neither a boolean nor a function. * @example * ```ts @@ -283,6 +292,7 @@ export class QueryObserver< TQueryData, TQueryKey >, + canFetch?: CanFetchOnQueryChange, ): void { const prevOptions = this.options const prevQuery = this.#currentQuery @@ -325,6 +335,7 @@ export class QueryObserver< prevQuery, this.options, prevOptions, + canFetch, ) ) { this.#executeFetch() @@ -367,6 +378,7 @@ export class QueryObserver< * Call `commit` after the render commits to apply the options and reuse the * reader's computation. An abandoned reader needs no cleanup. * @param options - The defaulted options used to read and commit the query result. + * @param canFetch - The fetch predicate for this read and commit. * @returns A reader with local snapshot and computation caches. */ createResultReader( @@ -377,6 +389,7 @@ export class QueryObserver< TQueryData, TQueryKey >, + canFetch?: CanFetchOnQueryChange, ): QueryObserverResultReader> { const readerOptions = { ...options } const { select, structuralSharing } = readerOptions @@ -408,6 +421,7 @@ export class QueryObserver< readerOptions, context, result, + canFetch, ) if (!shallowEqualObjects(nextResult, result)) { result = nextResult @@ -421,7 +435,7 @@ export class QueryObserver< // Reuse selections computed since the last read. getSnapshot() this.#resultContext = { ...context } - this.setOptions(readerOptions) + this.setOptions(readerOptions, canFetch) }, } } @@ -754,6 +768,7 @@ export class QueryObserver< * @param options - The observer options to compute the result with. * @param context - The selection and placeholder state reused between computations. * @param prevResult - The previous result used for structural sharing. + * @param canFetch - The fetch predicate for this read. * @returns The computed result. */ protected createResult( @@ -769,6 +784,7 @@ export class QueryObserver< prevResult = this.#currentResult as | QueryObserverResult | undefined, + canFetch?: CanFetchOnQueryChange, ): QueryObserverResult { const prevQuery = this.#currentQuery const prevOptions = this.options @@ -781,7 +797,13 @@ export class QueryObserver< const fetchOptimistically = options._optimisticResults && (this.hasListeners() - ? shouldFetchOptionally(query, prevQuery, options, prevOptions) + ? shouldFetchOptionally( + query, + prevQuery, + options, + prevOptions, + canFetch, + ) : shouldFetchOnMount(query, options)) const newState = fetchOptimistically ? { ...state, ...fetchState(state.data, query.options) } @@ -923,24 +945,18 @@ export class QueryObserver< const { notifyOnChangeProps } = this.options - if ( - notifyOnChangeProps === 'all' || - (notifyOnChangeProps !== 'none' && !this.#trackedProps.size) - ) { - return true + if (notifyOnChangeProps === 'none') { + return false } if ( - this.options.throwOnError && + notifyOnChangeProps === 'all' || + !this.#trackedProps.size || this.#currentResult.error !== prevResult.error ) { return true } - if (notifyOnChangeProps === 'none') { - return false - } - for (const key of this.#trackedProps) { if (this.#currentResult[key] !== prevResult[key]) { return true @@ -1072,19 +1088,21 @@ function shouldFetchOn( * @param prevQuery - The query observed with the previous options. * @param options - The new observer options. * @param prevOptions - The previous observer options. - * @returns `true` if the query changed or was disabled before, it isn't a suspense query in an - * error state, and it is stale. + * @param canFetch - The fetch predicate for this transition. + * @returns `true` if the query changed or was disabled before, retries on this transition + * are allowed, and the query is stale. */ function shouldFetchOptionally( query: Query, prevQuery: Query, options: QueryObserverOptionsBase, prevOptions: QueryObserverOptionsBase, + canFetch?: CanFetchOnQueryChange, ): boolean { return ( (query !== prevQuery || resolveQueryValue(prevOptions.enabled, query) === false) && - (!options.suspense || query.state.status !== 'error') && + canFetch?.(query) !== false && isStale(query, options) ) } diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 8f1aba69b66..5feaa73ec28 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -508,19 +508,6 @@ export interface InfiniteQueryPageParamsOptions< getNextPageParam: GetNextPageParamFunction } -/** @inline */ -export type ThrowOnError< - TQueryFnData, - TError, - TQueryData, - TQueryKey extends QueryKey, -> = - | boolean - | (( - error: TError, - query: Query, - ) => boolean) - /** * Shared options for default resolution and resolved observer state. * @internal @@ -618,20 +605,12 @@ export interface QueryObserverOptionsBase< * Controls when changes to the query result notify this observer's listeners. * Use `'all'` to notify on every result change. * Use `'none'` to suppress notifications while the query remains subscribed and can fetch. - * If `throwOnError` is set, changes to `error` still notify listeners. + * Changes to `error` notify listeners unless this is set to `'none'`. * * By default, adapters that track property reads notify listeners when a tracked property changes. * If no properties are tracked, every result change notifies listeners. */ notifyOnChangeProps?: NotifyOnChangeProps - /** - * Whether errors should be thrown instead of setting the `error` property. - * If set to `true` or `suspense` is `true`, all errors will be thrown to the error boundary. - * If set to `false` and `suspense` is `false`, errors are returned as state. - * If set to a function, it will be passed the error and the query, and it should return a boolean indicating whether to show the error in an error boundary (`true`) or return the error as state (`false`). - * @defaultValue false - */ - throwOnError?: ThrowOnError /** * This option can be used to transform or select a part of the data returned by the query function. It affects * the returned `data` value, but does not affect what gets stored in the query cache. @@ -640,12 +619,6 @@ export interface QueryObserverOptionsBase< * If the selector throws, the observer reports the error and can keep the last valid selection. */ select?: (data: TQueryData) => TData - /** - * If set to `true`, the query will suspend when `status === 'pending'` - * and throw errors when `status === 'error'`. - * @defaultValue false - */ - suspense?: boolean /** * If set, this value will be used as the placeholder data for this particular query observer while the query is still in the `loading` data and no initialData has been provided. * If the placeholder function throws, the observer reports the error with no data. The query state in the cache is unaffected. @@ -697,7 +670,7 @@ export type WithRequired = TTarget & { /** * The {@link QueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the - * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + * defaults, so `refetchOnReconnect` and `queryHash` are always set. */ export type DefaultedQueryObserverOptions< TQueryFnData = unknown, @@ -715,7 +688,7 @@ export type DefaultedQueryObserverOptions< TQueryKey, TPageParam >, - 'throwOnError' | 'refetchOnReconnect' | 'queryHash' + 'refetchOnReconnect' | 'queryHash' > /** @@ -742,7 +715,7 @@ export interface InfiniteQueryObserverOptions< /** * The {@link InfiniteQueryObserverOptions} after `QueryClient#defaultQueryOptions` has applied the - * defaults, so `throwOnError`, `refetchOnReconnect`, and `queryHash` are always set. + * defaults, so `refetchOnReconnect` and `queryHash` are always set. */ export type DefaultedInfiniteQueryObserverOptions< TQueryFnData = unknown, @@ -1952,23 +1925,14 @@ export interface MutationOptions< /** * The options of a `MutationObserver`, and of the hooks built on it like `useMutation`: the - * {@link MutationOptions}, plus `throwOnError`. + * {@link MutationOptions}. */ -export interface MutationObserverOptions< +export type MutationObserverOptions< TData = unknown, TError = DefaultError, TVariables = void, TOnMutateResult = unknown, -> extends MutationOptions { - /** - * Whether errors should be thrown instead of setting the `error` property. - * If set to `true`, all errors will be thrown to the nearest error boundary. - * If set to a function, it will be passed the error and should return a boolean indicating whether to throw the - * error (`true`) or return it as state (`false`). - * @defaultValue false - */ - throwOnError?: boolean | ((error: TError) => boolean) -} +> = MutationOptions /** * The callbacks that can be passed to `mutate` for a single call. They run after the callbacks of @@ -2341,10 +2305,7 @@ export interface QueryClientConfig { */ export interface DefaultOptions { /** Default options applied to every query, unless overridden per-query. */ - queries?: OmitKeyof< - QueryObserverOptionsBase, - 'suspense' | 'queryKey' - > + queries?: OmitKeyof, 'queryKey'> /** Default options applied to every mutation, unless overridden per-mutation. */ mutations?: MutationObserverOptions /** Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 9769214dbcb..8f25eec91ea 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -725,36 +725,6 @@ export function ensureQueryFn< return options.queryFn } -/** - * Resolves a `throwOnError` option to a boolean. - * If `throwOnError` is a function, it is called with `params` (e.g. the error and, depending on the caller, - * additional context such as the query or mutation) and its result is returned, allowing the throwing - * behavior to be decided per error. Otherwise, `throwOnError` itself is coerced to a boolean (`undefined` - * resolves to `false`). - * @param throwOnError - The `throwOnError` option: a boolean, a function that decides per error, or - * `undefined`. - * @param params - The arguments passed to `throwOnError` if it is a function. - * @returns Whether the error should be thrown. - * @example - * ```ts - * const throwOnError = - * query.state.error && typeof options.throwOnError === 'function' - * ? shouldThrowError(options.throwOnError, [query.state.error, query]) - * : options.throwOnError - * ``` - */ -export function shouldThrowError) => boolean>( - throwOnError: boolean | T | undefined, - params: Parameters, -): boolean { - // Allow throwOnError function to override throwing behavior on a per-error basis - if (typeof throwOnError === 'function') { - return throwOnError(...params) - } - - return !!throwOnError -} - export const fetchSignal = Symbol() /** Internal view of a context that can expose its signal without consuming it. */ diff --git a/packages/react-query/src/QueryClient.ts b/packages/react-query/src/QueryClient.ts new file mode 100644 index 00000000000..967601966d4 --- /dev/null +++ b/packages/react-query/src/QueryClient.ts @@ -0,0 +1,88 @@ +import { QueryClient as CoreQueryClient } from '@tanstack/query-core' +import type { + DefaultOptions as CoreDefaultOptions, + QueryClientConfig as CoreQueryClientConfig, + DefaultError, + MutationKey, + QueryKey, +} from '@tanstack/query-core' +import type { + ThrowOnError, + UseBaseQueryOptions, + UseMutationOptions, +} from './types' + +/** Client defaults, including the adapter's error boundary options. */ +export interface DefaultOptions< + TError = DefaultError, +> extends CoreDefaultOptions { + /** Default query options, including whether to throw errors to an error boundary. */ + queries?: CoreDefaultOptions['queries'] & + Pick, 'throwOnError'> + /** Default mutation options, including whether to throw errors to an error boundary. */ + mutations?: CoreDefaultOptions['mutations'] & + Pick, 'throwOnError'> +} + +/** Configuration for a query client with adapter-specific defaults. */ +export interface QueryClientConfig extends CoreQueryClientConfig { + /** Default options for all queries and mutations created through this client. */ + defaultOptions?: DefaultOptions +} + +/** A query client that accepts the adapter's error boundary options as defaults. */ +export interface QueryClient extends CoreQueryClient { + /** {@inheritDoc CoreQueryClient.getDefaultOptions} */ + getDefaultOptions: () => DefaultOptions + /** {@inheritDoc CoreQueryClient.setDefaultOptions} */ + setDefaultOptions: (options: DefaultOptions) => void + + /** {@inheritDoc CoreQueryClient.setQueryDefaults} */ + setQueryDefaults: < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + >( + queryKey: QueryKey, + options: Partial< + Omit< + UseBaseQueryOptions, + 'queryKey' | 'subscribed' + > + >, + ) => void + + /** {@inheritDoc CoreQueryClient.getQueryDefaults} */ + getQueryDefaults: (queryKey: QueryKey) => ReturnType< + CoreQueryClient['getQueryDefaults'] + > & { + throwOnError?: ThrowOnError + } + + /** {@inheritDoc CoreQueryClient.setMutationDefaults} */ + setMutationDefaults: < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + mutationKey: MutationKey, + options: Omit< + UseMutationOptions, + 'mutationKey' + >, + ) => void + + /** {@inheritDoc CoreQueryClient.getMutationDefaults} */ + getMutationDefaults: ( + mutationKey: MutationKey, + ) => ReturnType & + Pick, 'throwOnError'> +} + +/** Creates a query client. The constructor is shared with query-core. */ +export const QueryClient: { + new (config?: QueryClientConfig): QueryClient + readonly prototype: QueryClient +} = CoreQueryClient diff --git a/packages/react-query/src/QueryClientProvider.tsx b/packages/react-query/src/QueryClientProvider.tsx index d9c4108fb6d..2788b74b982 100644 --- a/packages/react-query/src/QueryClientProvider.tsx +++ b/packages/react-query/src/QueryClientProvider.tsx @@ -1,6 +1,6 @@ 'use client' import * as React from 'react' -import type { QueryClient } from '@tanstack/query-core' +import type { QueryClient } from './QueryClient' /** * The context that `useQueryClient` reads from. `QueryClientProvider` is the normal way to set it. diff --git a/packages/react-query/src/__tests__/suspense.test.tsx b/packages/react-query/src/__tests__/suspense.test.tsx index 22e0017f362..344a721a87b 100644 --- a/packages/react-query/src/__tests__/suspense.test.tsx +++ b/packages/react-query/src/__tests__/suspense.test.tsx @@ -54,7 +54,6 @@ describe('Suspense Timer Tests', () => { const options = queryClient.defaultQueryOptions({ queryKey: key, queryFn: () => sleep(10).then(() => 'data'), - suspense: true, }) const observer = new QueryObserver(queryClient, options) const errorResetBoundary = { @@ -87,7 +86,6 @@ describe('Suspense Timer Tests', () => { const options = queryClient.defaultQueryOptions({ queryKey: key, queryFn: () => sleep(10).then(() => 'data'), - suspense: true, }) const observer = new QueryObserver(queryClient, options) const errorResetBoundary = { diff --git a/packages/react-query/src/__tests__/useQueries.test.tsx b/packages/react-query/src/__tests__/useQueries.test.tsx index 2987133043c..7db21c8e98b 100644 --- a/packages/react-query/src/__tests__/useQueries.test.tsx +++ b/packages/react-query/src/__tests__/useQueries.test.tsx @@ -442,48 +442,83 @@ describe('useQueries', () => { expect(rendered.getByText('error boundary')).toBeInTheDocument() }) - it("should throw error if in one of queries' queryFn throws and throwOnError is in use while the combined result does not change", async () => { + it('sends an error to the boundary when combined data stays the same', async () => { vi.spyOn(console, 'error').mockReturnValue(undefined) - const key = createKey() + const queryKey = createKey() function Page() { const data = useQueries({ queries: [ { - queryKey: key, + queryKey, queryFn: () => - sleep(10).then(() => - Promise.reject(new Error('single query error')), - ), - throwOnError: true, + sleep(10).then(() => { + throw new Error('query failed') + }), retry: false, + throwOnError: true, }, ], combine: (results) => results.map((result) => result.data), }) - return
data: {String(data[0])}
} const rendered = renderWithClient( queryClient, - ( -
-
error boundary
-
{error.message}
-
- )} - > +
{error.message}
}>
, ) expect(rendered.getByText('data: undefined')).toBeInTheDocument() + await vi.advanceTimersByTimeAsync(10) + expect(rendered.getByText('query failed')).toBeInTheDocument() + }) - await vi.advanceTimersByTimeAsync(11) - expect(rendered.getByText('error boundary')).toBeInTheDocument() - expect(rendered.getByText('single query error')).toBeInTheDocument() + it('reports the query error before calling combine with a failed result', async () => { + vi.spyOn(console, 'error').mockReturnValue(undefined) + const queryKey = createKey() + const queryError = new Error('query failed') + const queryFn = () => Promise.reject(queryError) + const onError = vi.fn<(error: Error) => void>() + queryCache.config.onError = onError + + function Page() { + const data = useQueries({ + queries: [ + { + queryKey, + queryFn, + enabled: false, + retry: false, + throwOnError: true, + }, + ], + combine: ([result]) => { + if (result.isError) { + throw new Error('combine received a failed result') + } + return result.data + }, + }) + return
data: {String(data)}
+ } + + const rendered = renderWithClient( + queryClient, +
{error.message}
}> + +
, + ) + + expect(rendered.getByText('data: undefined')).toBeInTheDocument() + await expect( + queryClient.query({ queryKey, queryFn, retry: false }), + ).rejects.toBe(queryError) + await vi.advanceTimersByTimeAsync(0) + expect(onError).toHaveBeenCalledWith(queryError, expect.anything()) + expect(rendered.getByText('query failed')).toBeInTheDocument() }) it('should use provided custom queryClient', async () => { diff --git a/packages/react-query/src/__tests__/useQuery.test.tsx b/packages/react-query/src/__tests__/useQuery.test.tsx index edd9fb80c4b..984c78e0e72 100644 --- a/packages/react-query/src/__tests__/useQuery.test.tsx +++ b/packages/react-query/src/__tests__/useQuery.test.tsx @@ -2737,36 +2737,46 @@ describe('useQuery', () => { expect(rendered.getByText('Error test')).toBeInTheDocument() }) - it('should throw error if queryFn throws and throwOnError is in use', async () => { - vi.spyOn(console, 'error').mockReturnValue(undefined) - const key = createKey() + it.each([ + { notifyOnChangeProps: undefined, expected: 'error boundary' }, + { notifyOnChangeProps: 'none', expected: 'Error test' }, + ] as const)( + 'shows $expected with notifyOnChangeProps set to $notifyOnChangeProps', + async ({ notifyOnChangeProps, expected }) => { + vi.spyOn(console, 'error').mockReturnValue(undefined) + const key = createKey() + const throwOnError = vi.fn<() => boolean>(() => true) + const queryFn = async () => { + throw new Error('Error test') + } + queryClient.setQueryDefaults(key, { throwOnError }) + await expect( + queryClient.query({ queryKey: key, queryFn, retry: false }), + ).rejects.toThrow('Error test') - function Page() { - const { status, error } = useQuery({ - queryKey: key, - queryFn: () => Promise.reject(new Error('Error test')), - retry: false, - throwOnError: true, - }) + function Page() { + const { error } = useQuery({ + queryKey: key, + queryFn, + enabled: false, + notifyOnChangeProps, + }) + return
{error?.message}
+ } - return ( -
-

{status}

-

{error}

-
+ const rendered = renderWithClient( + queryClient, +
error boundary
}> + +
, ) - } - - const rendered = renderWithClient( - queryClient, -
error boundary
}> - -
, - ) - await vi.advanceTimersByTimeAsync(0) - expect(rendered.getByText('error boundary')).toBeInTheDocument() - }) + expect(rendered.getByText(expected)).toBeInTheDocument() + expect(throwOnError.mock.calls.length === 0).toBe( + notifyOnChangeProps === 'none', + ) + }, + ) it('should throw error if queryFn rejects with a falsy error and throwOnError is in use', async () => { vi.spyOn(console, 'error').mockReturnValue(undefined) diff --git a/packages/react-query/src/errorBoundaryUtils.ts b/packages/react-query/src/errorBoundaryUtils.ts index 71f6483546f..5bb53613c19 100644 --- a/packages/react-query/src/errorBoundaryUtils.ts +++ b/packages/react-query/src/errorBoundaryUtils.ts @@ -1,14 +1,9 @@ 'use client' -import { shouldThrowError } from '@tanstack/query-core' import * as React from 'react' -import type { - DefaultedQueryObserverOptions, - Query, - QueryKey, - QueryObserverResult, - ThrowOnError, -} from '@tanstack/query-core' +import { shouldThrowError } from './utils' +import type { Query, QueryKey, QueryObserverResult } from '@tanstack/query-core' import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' +import type { DefaultedQueryOptions, ThrowOnError } from './types' /** * Turns off `retryOnMount` for a query that throws its errors (with `suspense` or `throwOnError`), @@ -17,15 +12,16 @@ import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' * @param options - The defaulted query options to adjust. * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. * @param query - The query, used to evaluate a `throwOnError` function against its error. + * @param suspense - Whether the hook uses Suspense. */ -export const ensurePreventErrorBoundaryRetry = < +export const prepareErrorBoundaryOptions = < TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, >( - options: DefaultedQueryObserverOptions< + options: DefaultedQueryOptions< TQueryFnData, TError, TData, @@ -34,7 +30,12 @@ export const ensurePreventErrorBoundaryRetry = < >, errorResetBoundary: QueryErrorResetBoundaryValue, query: Query | undefined, + suspense: boolean, ) => { + if (options.notifyOnChangeProps === 'none') { + options.throwOnError = false + } + const throwOnError = query?.state.status === 'error' && typeof options.throwOnError === 'function' @@ -44,7 +45,7 @@ export const ensurePreventErrorBoundaryRetry = < ]) : options.throwOnError - if (options.suspense || throwOnError) { + if (suspense || throwOnError) { // Prevent retrying failed query if the error boundary has not been reset yet if (!errorResetBoundary.isReset()) { options.retryOnMount = false @@ -88,7 +89,7 @@ export const getHasError = < }: { result: QueryObserverResult errorResetBoundary: QueryErrorResetBoundaryValue - throwOnError: ThrowOnError + throwOnError?: ThrowOnError query: Query | undefined suspense: boolean | undefined }) => { diff --git a/packages/react-query/src/index.ts b/packages/react-query/src/index.ts index c2a164ed1d6..adf6bf7849a 100644 --- a/packages/react-query/src/index.ts +++ b/packages/react-query/src/index.ts @@ -3,6 +3,9 @@ // Re-export core // oxlint-disable-next-line tanstack-query/no-restricted-syntax export * from '@tanstack/query-core' +export { QueryClient } from './QueryClient' +export type { DefaultOptions, QueryClientConfig } from './QueryClient' +export type { ThrowOnError } from './types' // React Query export type { diff --git a/packages/react-query/src/suspense.ts b/packages/react-query/src/suspense.ts index 1fb8f56967d..202629a55c6 100644 --- a/packages/react-query/src/suspense.ts +++ b/packages/react-query/src/suspense.ts @@ -43,31 +43,29 @@ export const defaultThrowOnError = < * collected. A `'static'` `staleTime` is kept as is. Mutates the options. * @param defaultedOptions - The defaulted query options to adjust. */ -export const ensureSuspenseTimers = ( +export const prepareSuspenseOptions = ( defaultedOptions: DefaultedQueryObserverOptions, ) => { - if (defaultedOptions.suspense) { - // Handle staleTime to ensure minimum 1000ms in Suspense mode - // This prevents unnecessary refetching when components remount after suspending - const MIN_SUSPENSE_TIME_MS = 1000 - - const clamp = (value: number | 'static' | undefined) => - value === 'static' - ? value - : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) - - const originalStaleTime = defaultedOptions.staleTime - defaultedOptions.staleTime = - typeof originalStaleTime === 'function' - ? (...args) => clamp(originalStaleTime(...args)) - : clamp(originalStaleTime) - - if (typeof defaultedOptions.gcTime === 'number') { - defaultedOptions.gcTime = Math.max( - defaultedOptions.gcTime, - MIN_SUSPENSE_TIME_MS, - ) - } + // Handle staleTime to ensure minimum 1000ms in Suspense mode + // This prevents unnecessary refetching when components remount after suspending + const MIN_SUSPENSE_TIME_MS = 1000 + + const clamp = (value: number | 'static' | undefined) => + value === 'static' + ? value + : Math.max(value ?? MIN_SUSPENSE_TIME_MS, MIN_SUSPENSE_TIME_MS) + + const originalStaleTime = defaultedOptions.staleTime + defaultedOptions.staleTime = + typeof originalStaleTime === 'function' + ? (...args) => clamp(originalStaleTime(...args)) + : clamp(originalStaleTime) + + if (typeof defaultedOptions.gcTime === 'number') { + defaultedOptions.gcTime = Math.max( + defaultedOptions.gcTime, + MIN_SUSPENSE_TIME_MS, + ) } } @@ -142,8 +140,6 @@ const useReadSuspenseQuery = ( client: QueryClient, errorResetBoundary: QueryErrorResetBoundaryValue, ) => { - if (!defaultedOptions.suspense) return - const snapshot = reader.getSnapshot() const query = client.getQueryCache().build(client, defaultedOptions) const suspend = shouldSuspend(snapshot, errorResetBoundary, query) @@ -160,9 +156,13 @@ const useReadSuspenseQuery = ( } } +const canFetchOnQueryChange = (query: Query) => + query.state.status !== 'error' + /** Supplies Suspense behavior for one query. */ export const suspenseQueryPolicy = { - prepare: ensureSuspenseTimers, + prepare: prepareSuspenseOptions, + canFetchOnQueryChange, readQuery: useReadSuspenseQuery, } @@ -177,7 +177,7 @@ const useReadSuspenseQueries = ( const suspensePromises = snapshot.map((result, index) => { const opts = defaultedQueries[index] - if (!opts?.suspense) { + if (!opts) { return undefined } @@ -209,6 +209,9 @@ const useReadSuspenseQueries = ( /** Supplies Suspense behavior for parallel queries. */ export const suspenseQueriesPolicy = { - prepare: ensureSuspenseTimers, + prepare: prepareSuspenseOptions, + canFetchOnQueryChange, readQueries: useReadSuspenseQueries, + canCombine: (results: Array) => + results.every((result) => result.data !== undefined), } diff --git a/packages/react-query/src/types.ts b/packages/react-query/src/types.ts index 269b7955b41..e912f65a811 100644 --- a/packages/react-query/src/types.ts +++ b/packages/react-query/src/types.ts @@ -2,6 +2,7 @@ import type { DefaultError, + DefaultedQueryObserverOptions, DefinedInfiniteQueryObserverResult, DefinedQueryObserverResult, DistributiveOmit, @@ -15,6 +16,7 @@ import type { MutationObserverResult, OmitKeyof, Override, + Query, QueryExecuteOptions, QueryKey, QueryObserverOptions, @@ -23,6 +25,50 @@ import type { SkipToken, } from '@tanstack/query-core' +/** A boolean or predicate that sends query errors to the nearest error boundary. */ +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) + +interface QueryErrorOptions< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> { + /** + * Set to `true` to throw query errors to the nearest error boundary. + * A predicate receives the error and query and decides whether to throw. + * This option is ignored when `notifyOnChangeProps` is `'none'`. + * @defaultValue false + */ + throwOnError?: ThrowOnError +} + +/** @internal */ +export type DefaultedQueryOptions< + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + TQueryKey extends QueryKey = QueryKey, +> = DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> & + QueryErrorOptions + /** * {@link UseBaseQueryOptions} with all type parameters set to `any`, useful when the specific types aren't * relevant, e.g. when accepting options for any query in a helper function. @@ -51,13 +97,10 @@ export interface UseBaseQueryOptions< TData = TQueryFnData, TQueryData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> extends QueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryData, - TQueryKey -> { +> + extends + QueryObserverOptions, + QueryErrorOptions { /** * Set this to `false` to unsubscribe this observer from updates to the query cache. * @defaultValue true @@ -149,8 +192,7 @@ export type UsePrefetchInfiniteQueryOptions< */ export type AnyUseQueryOptions = UseQueryOptions /** - * The options accepted by `useQuery`. Same as {@link UseBaseQueryOptions}, minus `suspense` (which - * `react-query` derives from which hook you call rather than exposing as an option). + * The options accepted by `useQuery`. Uses the options from {@link UseBaseQueryOptions}. * @template TQueryFnData - The type your `queryFn` resolves to. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs. Defaults to `TQueryFnData` when no @@ -162,9 +204,12 @@ export interface UseQueryOptions< TError = DefaultError, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey, -> extends OmitKeyof< - UseBaseQueryOptions, - 'suspense' +> extends UseBaseQueryOptions< + TQueryFnData, + TError, + TData, + TQueryFnData, + TQueryKey > {} /** @@ -218,8 +263,7 @@ export type AnyUseInfiniteQueryOptions = UseInfiniteQueryOptions< > /** * The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} from - * `@tanstack/query-core` with the `react-query`-specific `subscribed` option, minus `suspense` (which - * `react-query` derives from which hook you call rather than exposing as an option). + * `@tanstack/query-core` with `subscribed` and `throwOnError`. * @template TQueryFnData - The type of a single page, as your `queryFn` resolves it. * @template TError - The type of errors your `queryFn` may throw. * @template TData - The type `data` ends up as after `select` runs — defaults to `InfiniteData`, @@ -233,16 +277,21 @@ export interface UseInfiniteQueryOptions< TData = InfiniteData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> extends OmitKeyof< - InfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - 'suspense' -> { +> + extends + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + QueryErrorOptions< + TQueryFnData, + TError, + InfiniteData, + TQueryKey + > { /** * Set this to `false` to unsubscribe this observer from updates to the query cache. * @defaultValue true @@ -371,7 +420,7 @@ export type UseSuspenseInfiniteQueryResult< export type AnyUseMutationOptions = UseMutationOptions /** * The options accepted by `useMutation`. Same as {@link MutationObserverOptions} from `@tanstack/query-core`, - * minus the internal `_defaulted` flag. + * with `throwOnError` and without the internal `_defaulted` flag. * @template TData - The type your mutation function resolves to. * @template TError - The type of errors your mutation function may throw. * @template TVariables - The type of the variable passed to `mutate`/`mutateAsync`. @@ -386,7 +435,14 @@ export interface UseMutationOptions< > extends OmitKeyof< MutationObserverOptions, '_defaulted' -> {} +> { + /** + * Set to `true` to throw mutation errors to the nearest error boundary. + * A predicate receives the error and decides whether to throw. + * @defaultValue false + */ + throwOnError?: boolean | ((error: TError) => boolean) +} /** * The type of `mutate`, as returned by `useMutation`. Forwards the variables (and an optional per-call diff --git a/packages/react-query/src/useBaseQuery.ts b/packages/react-query/src/useBaseQuery.ts index b901e03f6ee..443a9ccfa28 100644 --- a/packages/react-query/src/useBaseQuery.ts +++ b/packages/react-query/src/useBaseQuery.ts @@ -5,8 +5,8 @@ import { useIsRestoring } from './IsRestoringProvider' import { useQueryClient } from './QueryClientProvider' import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' import { - ensurePreventErrorBoundaryRetry, getHasError, + prepareErrorBoundaryOptions, useClearResetErrorBoundary, } from './errorBoundaryUtils' import type { @@ -16,7 +16,7 @@ import type { QueryObserverResult, } from '@tanstack/query-core' import type { suspenseQueryPolicy } from './suspense' -import type { UseBaseQueryOptions } from './types' +import type { DefaultedQueryOptions, UseBaseQueryOptions } from './types' /** * Base implementation shared by `useQuery`, `useInfiniteQuery`, `useSuspenseQuery`, and @@ -61,10 +61,13 @@ export function useBaseQuery< const isRestoring = useIsRestoring() const errorResetBoundary = useQueryErrorResetBoundary() const client = useQueryClient(queryClient) - const defaultedOptions = client.defaultQueryOptions({ - ...options, - suspense: !!suspense, - }) + const defaultedOptions: DefaultedQueryOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > = client.defaultQueryOptions({ ...options }) const query = client .getQueryCache() @@ -90,7 +93,12 @@ export function useBaseQuery< : undefined suspense?.prepare(defaultedOptions) - ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions( + defaultedOptions, + errorResetBoundary, + query, + !!suspense, + ) useClearResetErrorBoundary(errorResetBoundary) const [observer] = React.useState( @@ -101,7 +109,10 @@ export function useBaseQuery< ), ) - const reader = observer.createResultReader(defaultedOptions) + const reader = observer.createResultReader( + defaultedOptions, + suspense?.canFetchOnQueryChange, + ) suspense?.readQuery( defaultedOptions, @@ -142,7 +153,7 @@ export function useBaseQuery< errorResetBoundary, throwOnError: defaultedOptions.throwOnError, query, - suspense: defaultedOptions.suspense, + suspense: !!suspense, }) ) { throw result.error diff --git a/packages/react-query/src/useMutation.ts b/packages/react-query/src/useMutation.ts index 821aaa38def..42801719972 100644 --- a/packages/react-query/src/useMutation.ts +++ b/packages/react-query/src/useMutation.ts @@ -1,12 +1,8 @@ 'use client' -import { - MutationObserver, - noop, - notifyManager, - shouldThrowError, -} from '@tanstack/query-core' +import { MutationObserver, noop, notifyManager } from '@tanstack/query-core' import * as React from 'react' import { useQueryClient } from './QueryClientProvider' +import { shouldThrowError } from './utils' import type { DefaultError, QueryClient } from '@tanstack/query-core' import type { UseMutateFunction, @@ -230,9 +226,15 @@ export function useMutation< [observer], ) + const observerOptions: UseMutationOptions< + TData, + TError, + TVariables, + TOnMutateResult + > = observer.options if ( result.error && - shouldThrowError(observer.options.throwOnError, [result.error]) + shouldThrowError(observerOptions.throwOnError, [result.error]) ) { throw result.error } diff --git a/packages/react-query/src/useQueries.ts b/packages/react-query/src/useQueries.ts index f62021dcb0b..0be66f257b1 100644 --- a/packages/react-query/src/useQueries.ts +++ b/packages/react-query/src/useQueries.ts @@ -5,8 +5,8 @@ import { useIsRestoring } from './IsRestoringProvider' import { useQueryClient } from './QueryClientProvider' import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary' import { - ensurePreventErrorBoundaryRetry, getHasError, + prepareErrorBoundaryOptions, useClearResetErrorBoundary, } from './errorBoundaryUtils' import type { @@ -17,12 +17,13 @@ import type { QueryClient, QueryFunction, QueryKey, - QueryObserverOptions, - ThrowOnError, + QueryObserverResult, } from '@tanstack/query-core' import type { suspenseQueriesPolicy } from './suspense' import type { + DefaultedQueryOptions, DefinedUseQueryResult, + ThrowOnError, UseQueryOptions, UseQueryResult, } from './types' @@ -400,10 +401,8 @@ export function useBaseQueries< const defaultedQueries = React.useMemo( () => queries.map((opts) => { - const defaultedOptions = client.defaultQueryOptions({ - ...opts, - suspense: !!suspense, - } as QueryObserverOptions) + const defaultedOptions: DefaultedQueryOptions = + client.defaultQueryOptions({ ...opts }) // Make sure the results are already in fetching state before subscribing or updating options defaultedOptions._optimisticResults = isRestoring @@ -412,31 +411,59 @@ export function useBaseQueries< ? 'optimistic' : undefined + suspense?.prepare(defaultedOptions) return defaultedOptions }), [queries, client, isRestoring, subscribed, suspense], ) defaultedQueries.forEach((queryOptions) => { - suspense?.prepare(queryOptions) const query = client.getQueryCache().get(queryOptions.queryHash) - ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions( + queryOptions, + errorResetBoundary, + query, + !!suspense, + ) }) useClearResetErrorBoundary(errorResetBoundary) + const observerOptions = options as QueriesObserverOptions + const [observer] = React.useState( () => new QueriesObserver( client, defaultedQueries, - options as QueriesObserverOptions, + observerOptions, ), ) + const findErrorResult = (results: Array) => + results.find((result, index) => { + const query = defaultedQueries[index] + return ( + result.isError && + query && + getHasError({ + result, + errorResetBoundary, + throwOnError: query.throwOnError, + query: client.getQueryCache().get(query.queryHash), + suspense: !!suspense, + }) + ) + }) + const reader = observer.createResultReader( defaultedQueries, - options as QueriesObserverOptions, + observerOptions, + { + canFetchOnQueryChange: suspense?.canFetchOnQueryChange, + canCombine: (results) => + suspense?.canCombine(results) !== false && !findErrorResult(results), + }, ) suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) @@ -465,20 +492,7 @@ export function useBaseQueries< reader.getSnapshot, ) - const firstErrorResult = results.find((result, index) => { - const query = defaultedQueries[index] - return ( - query && - getHasError({ - result, - errorResetBoundary, - throwOnError: query.throwOnError, - query: client.getQueryCache().get(query.queryHash), - suspense: query.suspense, - }) - ) - }) - + const firstErrorResult = findErrorResult(results) if (firstErrorResult) { throw firstErrorResult.error } diff --git a/packages/react-query/src/useSuspenseQueries.ts b/packages/react-query/src/useSuspenseQueries.ts index 6cd573fef01..1181fcd8ecf 100644 --- a/packages/react-query/src/useSuspenseQueries.ts +++ b/packages/react-query/src/useSuspenseQueries.ts @@ -9,9 +9,12 @@ import type { QueryClient, QueryFunction, QueryKey, - ThrowOnError, } from '@tanstack/query-core' -import type { UseSuspenseQueryOptions, UseSuspenseQueryResult } from './types' +import type { + ThrowOnError, + UseSuspenseQueryOptions, + UseSuspenseQueryResult, +} from './types' // `placeholderData` functions in useQueries never receive previous query data. type UseSuspenseQueryOptionsForUseSuspenseQueries< diff --git a/packages/react-query/src/utils.ts b/packages/react-query/src/utils.ts new file mode 100644 index 00000000000..5a071fe7290 --- /dev/null +++ b/packages/react-query/src/utils.ts @@ -0,0 +1,16 @@ +/** + * Resolves the adapter's error boundary option. + * @param throwOnError - A boolean or a predicate. + * @param params - The arguments passed to the predicate. + * @returns Whether to throw the error. + */ +export function shouldThrowError) => boolean>( + throwOnError: boolean | T | undefined, + params: Parameters, +): boolean { + if (typeof throwOnError === 'function') { + return throwOnError(...params) + } + + return !!throwOnError +} diff --git a/packages/solid-query/src/QueryClient.ts b/packages/solid-query/src/QueryClient.ts index 4ec15b8af19..8f07c29a2a8 100644 --- a/packages/solid-query/src/QueryClient.ts +++ b/packages/solid-query/src/QueryClient.ts @@ -2,12 +2,15 @@ import { QueryClient as QueryCoreClient } from '@tanstack/query-core' import type { DefaultOptions as CoreDefaultOptions, DefaultError, + InfiniteData, + MutationKey, OmitKeyof, QueryClientConfig as QueryCoreClientConfig, InfiniteQueryObserverOptions as QueryCoreInfiniteQueryObserverOptions, QueryObserverOptions as QueryCoreObserverOptions, QueryKey, } from '@tanstack/query-core' +import type { MutationOptions, ThrowOnError } from './types' /** * The core `QueryObserverOptions`, with Solid's `reconcile` option added. @@ -35,8 +38,14 @@ export interface QueryObserverOptions< TQueryKey, TPageParam >, - 'structuralSharing' | 'suspense' + 'structuralSharing' > { + /** + * A boolean or predicate that sends errors to the nearest error boundary. + * This option is ignored when `notifyOnChangeProps` is `'none'`. + * @defaultValue false + */ + throwOnError?: ThrowOnError /** * Set this to a reconciliation key to enable reconciliation between query results. * Set this to `false` to disable reconciliation between query results. @@ -71,8 +80,20 @@ export interface InfiniteQueryObserverOptions< TQueryKey, TPageParam >, - 'structuralSharing' | 'suspense' + 'structuralSharing' > { + /** + * A boolean or predicate that sends errors to the nearest error boundary. + * This option is ignored when `notifyOnChangeProps` is `'none'`. + * @defaultValue false + */ + throwOnError?: ThrowOnError< + TQueryFnData, + TError, + InfiniteData, + TQueryKey + > + /** * Set this to a reconciliation key to enable reconciliation between query results. * Set this to `false` to disable reconciliation between query results. @@ -101,7 +122,10 @@ export interface DefaultOptions< NonNullable['queries']>, 'structuralSharing' > & - Pick, 'reconcile'> + Pick, 'reconcile' | 'throwOnError'> + /** Default mutation options, including whether to throw errors to an error boundary. */ + mutations?: CoreDefaultOptions['mutations'] & + Pick, 'throwOnError'> } /** @@ -119,6 +143,43 @@ export interface QueryClientConfig extends QueryCoreClientConfig { * `reconcile` option. */ export class QueryClient extends QueryCoreClient { + declare getDefaultOptions: () => DefaultOptions + declare setDefaultOptions: (options: DefaultOptions) => void + declare getQueryDefaults: ( + queryKey: QueryKey, + ) => ReturnType & + Pick, 'throwOnError'> + declare getMutationDefaults: ( + mutationKey: MutationKey, + ) => ReturnType & + Pick, 'throwOnError'> + declare setQueryDefaults: < + TQueryFnData = unknown, + TError = DefaultError, + TData = TQueryFnData, + TQueryData = TQueryFnData, + >( + queryKey: QueryKey, + options: Partial< + Omit< + QueryObserverOptions, + 'queryKey' | 'reconcile' + > + >, + ) => void + declare setMutationDefaults: < + TData = unknown, + TError = DefaultError, + TVariables = void, + TOnMutateResult = unknown, + >( + mutationKey: MutationKey, + options: Omit< + MutationOptions, + 'mutationKey' + >, + ) => void + constructor(config: QueryClientConfig = {}) { super(config) } diff --git a/packages/solid-query/src/index.ts b/packages/solid-query/src/index.ts index 742293bdd2f..2fe6ca2f3f0 100644 --- a/packages/solid-query/src/index.ts +++ b/packages/solid-query/src/index.ts @@ -18,6 +18,7 @@ export type { InfiniteQueryOptions, MutationOptions, QueryOptions, + ThrowOnError, UseBaseMutationResult, UseBaseQueryOptions, UseBaseQueryResult, diff --git a/packages/solid-query/src/types.ts b/packages/solid-query/src/types.ts index b6b57036703..aaa5f2f60cb 100644 --- a/packages/solid-query/src/types.ts +++ b/packages/solid-query/src/types.ts @@ -10,6 +10,7 @@ import type { MutationObserverResult, OmitKeyof, Override, + Query, QueryKey, QueryObserverResult, } from '@tanstack/query-core' @@ -236,7 +237,14 @@ export interface MutationOptions< > extends OmitKeyof< MutationObserverOptions, '_defaulted' -> {} +> { + /** + * Set to `true` to throw mutation errors to the nearest error boundary. + * A predicate receives the error and decides whether to throw. + * @defaultValue false + */ + throwOnError?: boolean | ((error: TError) => boolean) +} /** * The accessor `useMutation` expects as its first argument — Solid re-evaluates it reactively, so callbacks @@ -334,3 +342,16 @@ export type UseMutationResult< TVariables = unknown, TOnMutateResult = unknown, > = UseBaseMutationResult + +/** A boolean or predicate that sends query errors to the nearest error boundary. */ +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) diff --git a/packages/solid-query/src/useBaseQuery.ts b/packages/solid-query/src/useBaseQuery.ts index 72e99564874..d23535f359c 100644 --- a/packages/solid-query/src/useBaseQuery.ts +++ b/packages/solid-query/src/useBaseQuery.ts @@ -1,7 +1,7 @@ // Had to disable the lint rule because isServer type is defined as false // in solid-js/web package. I'll create a GitHub issue with them to see // why that happens. -import { hydrate, notifyManager, shouldThrowError } from '@tanstack/query-core' +import { hydrate, notifyManager } from '@tanstack/query-core' import { createComputed, createMemo, @@ -14,7 +14,9 @@ import { createStore, reconcile, unwrap } from 'solid-js/store' import { isServer } from 'solid-js/web' import { useQueryClientResolver } from './QueryClientProvider' import { useIsRestoring } from './isRestoring' +import { shouldThrowError } from './utils' import type { + DefaultedQueryObserverOptions, Query, QueryKey, QueryObserver, @@ -22,7 +24,7 @@ import type { } from '@tanstack/query-core' import type { Accessor, Signal } from 'solid-js' import type { QueryClient } from './QueryClient' -import type { UseBaseQueryOptions } from './types' +import type { ThrowOnError, UseBaseQueryOptions } from './types' /** * Applies the `reconcile` option when writing a new observer result into the store. @@ -146,7 +148,15 @@ export function useBaseQuery< let unsubscribeQueued = false const defaultedOptions = createMemo(() => { - const defaultOptions = client().defaultQueryOptions(options()) + const defaultOptions: DefaultedQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey + > & { + throwOnError?: ThrowOnError + } = client().defaultQueryOptions(options()) defaultOptions._optimisticResults = isRestoring() ? 'isRestoring' : 'optimistic' @@ -277,12 +287,15 @@ export function useBaseQuery< unsubscribe = createClientSubscriber() } obs.updateResult() + const observerOptions: typeof obs.options & + Pick = obs.options if ( observerResult.isError && !observerResult.isFetching && !isRestoring() && - shouldThrowError(obs.options.throwOnError, [ + observerOptions.notifyOnChangeProps !== 'none' && + shouldThrowError(observerOptions.throwOnError, [ observerResult.error, obs.getCurrentQuery(), ]) diff --git a/packages/solid-query/src/useMutation.ts b/packages/solid-query/src/useMutation.ts index 87d8810988e..627149bdcb4 100644 --- a/packages/solid-query/src/useMutation.ts +++ b/packages/solid-query/src/useMutation.ts @@ -1,7 +1,8 @@ -import { MutationObserver, noop, shouldThrowError } from '@tanstack/query-core' +import { MutationObserver, noop } from '@tanstack/query-core' import { createComputed, createMemo, on, onCleanup } from 'solid-js' import { createStore } from 'solid-js/store' import { useQueryClientResolver } from './QueryClientProvider' +import { shouldThrowError } from './utils' import type { DefaultError } from '@tanstack/query-core' import type { Accessor } from 'solid-js' import type { QueryClient } from './QueryClient' @@ -211,9 +212,10 @@ export function useMutation< on( () => state.status, () => { + const observerOptions: ReturnType = observer.options if ( state.isError && - shouldThrowError(observer.options.throwOnError, [state.error]) + shouldThrowError(observerOptions.throwOnError, [state.error]) ) { throw state.error } diff --git a/packages/solid-query/src/useQueries.ts b/packages/solid-query/src/useQueries.ts index cf927a5dcf0..78e55ebeb39 100644 --- a/packages/solid-query/src/useQueries.ts +++ b/packages/solid-query/src/useQueries.ts @@ -22,11 +22,10 @@ import type { QueryKey, QueryObserverOptions, QueryObserverResult, - ThrowOnError, } from '@tanstack/query-core' import type { Accessor } from 'solid-js' import type { QueryClient } from './QueryClient' -import type { QueryOptions, UseQueryResult } from './types' +import type { QueryOptions, ThrowOnError, UseQueryResult } from './types' // This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`. // `placeholderData` function does not have a parameter diff --git a/packages/solid-query/src/utils.ts b/packages/solid-query/src/utils.ts new file mode 100644 index 00000000000..5a071fe7290 --- /dev/null +++ b/packages/solid-query/src/utils.ts @@ -0,0 +1,16 @@ +/** + * Resolves the adapter's error boundary option. + * @param throwOnError - A boolean or a predicate. + * @param params - The arguments passed to the predicate. + * @returns Whether to throw the error. + */ +export function shouldThrowError) => boolean>( + throwOnError: boolean | T | undefined, + params: Parameters, +): boolean { + if (typeof throwOnError === 'function') { + return throwOnError(...params) + } + + return !!throwOnError +} diff --git a/packages/svelte-query/src/createQueries.svelte.ts b/packages/svelte-query/src/createQueries.svelte.ts index 85efd845760..5fd551281a7 100644 --- a/packages/svelte-query/src/createQueries.svelte.ts +++ b/packages/svelte-query/src/createQueries.svelte.ts @@ -11,7 +11,6 @@ import type { QueryClient, QueryFunction, QueryKey, - ThrowOnError, } from '@tanstack/query-core' import type { Accessor, @@ -65,7 +64,10 @@ type GetCreateQueryOptionsForCreateQueries = | QueryFunction | SkipTokenForCreateQueries select?: (data: any) => infer TData - throwOnError?: ThrowOnError + retry?: + | boolean + | number + | ((failureCount: number, error: infer TError) => boolean) } ? CreateQueryOptionsForCreateQueries< TQueryFnData, @@ -114,7 +116,10 @@ type GetCreateQueryResult = | QueryFunction | SkipTokenForCreateQueries select?: (data: any) => infer TData - throwOnError?: ThrowOnError + retry?: + | boolean + | number + | ((failureCount: number, error: infer TError) => boolean) } ? GetDefinedOrUndefinedQueryResult< T, diff --git a/packages/svelte-query/tests/createQuery/createQuery.svelte.test.ts b/packages/svelte-query/tests/createQuery/createQuery.svelte.test.ts index d93d93e3a0a..d01c6f197e8 100644 --- a/packages/svelte-query/tests/createQuery/createQuery.svelte.test.ts +++ b/packages/svelte-query/tests/createQuery/createQuery.svelte.test.ts @@ -1536,26 +1536,6 @@ describe('createQuery', () => { expect(rendered.getByTestId('error')).toHaveTextContent('Error test') }) - it('should set status to error instead of throwing when error should not be thrown', async () => { - const key = createKey() - - const rendered = render(Base, { - props: { - queryClient, - options: () => ({ - queryKey: key, - queryFn: () => Promise.reject(new Error('Local Error')), - retry: false, - throwOnError: (err: Error) => err.message !== 'Local Error', - }), - }, - }) - - await vi.advanceTimersByTimeAsync(0) - expect(rendered.getByTestId('status')).toHaveTextContent('error') - expect(rendered.getByTestId('error')).toHaveTextContent('Local Error') - }) - it( 'should support changing provided query client', withEffectRoot(() => { diff --git a/packages/vue-query/src/index.ts b/packages/vue-query/src/index.ts index 67a1008284b..14554e45c90 100644 --- a/packages/vue-query/src/index.ts +++ b/packages/vue-query/src/index.ts @@ -46,7 +46,12 @@ export type { UseMutationOptions, UseMutationReturnType, } from './useMutation' -export type { MutationOptions } from './types' +export type { + DefaultOptions, + MutationOptions, + QueryClientConfig, + ThrowOnError, +} from './types' export type { UseQueriesOptions, UseQueriesResults } from './useQueries' export type { MutationStateOptions, diff --git a/packages/vue-query/src/queryClient.ts b/packages/vue-query/src/queryClient.ts index dcc021cce55..f3f5c5b3b13 100644 --- a/packages/vue-query/src/queryClient.ts +++ b/packages/vue-query/src/queryClient.ts @@ -6,7 +6,6 @@ import { cloneDeepUnref } from './utils' import type { CancelOptions, DefaultError, - DefaultOptions, InferDataFromTag, InferErrorFromTag, InfiniteData, @@ -15,7 +14,6 @@ import type { InvalidateQueryFilters, MutationFilters, MutationKey, - MutationObserverOptions, QueryExecuteOptions, QueryFilters, QueryKey, @@ -30,9 +28,11 @@ import type { import type { Ref } from 'vue' import type { UseQueryOptions } from './queryOptions' import type { + DefaultOptions, MaybeRef, MaybeRefDeep, MaybeRefOrGetter, + MutationOptions, NoUnknown, QueryClientConfig, } from './types' @@ -453,6 +453,8 @@ export class QueryClient extends QC { return super.infiniteQuery(cloneDeepUnref(options)) } + declare getDefaultOptions: () => DefaultOptions + override setDefaultOptions(options: MaybeRefDeep): void { super.setDefaultOptions(cloneDeepUnref(options)) } @@ -478,7 +480,8 @@ export class QueryClient extends QC { override getQueryDefaults( queryKey: MaybeRefDeep, - ): ReturnType { + ): ReturnType & + Pick['queries']>, 'throwOnError'> { return super.getQueryDefaults(cloneDeepUnref(queryKey)) } @@ -490,7 +493,7 @@ export class QueryClient extends QC { >( mutationKey: MaybeRefDeep, options: MaybeRefDeep< - MutationObserverOptions + MutationOptions >, ): void { super.setMutationDefaults( @@ -501,7 +504,7 @@ export class QueryClient extends QC { override getMutationDefaults( mutationKey: MaybeRefDeep, - ): MutationObserverOptions { + ): MutationOptions { return super.getMutationDefaults(cloneDeepUnref(mutationKey)) } } diff --git a/packages/vue-query/src/queryOptions.ts b/packages/vue-query/src/queryOptions.ts index 4994ae85501..c965a0fb2e5 100644 --- a/packages/vue-query/src/queryOptions.ts +++ b/packages/vue-query/src/queryOptions.ts @@ -1,11 +1,11 @@ import type { + QueryObserverOptions as CoreQueryObserverOptions, DefaultError, InitialDataFunction, NonUndefinedGuard, QueryBooleanOption, QueryKey, QueryKeyWithDataTag, - QueryObserverOptions, } from '@tanstack/query-core' import type { DeepUnwrapRef, @@ -13,8 +13,31 @@ import type { MaybeRefDeep, MaybeRefOrGetter, ShallowOption, + ThrowOnError, } from './types' +type QueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey extends QueryKey, +> = CoreQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryData, + TQueryKey +> & { + /** + * Set to `true` to send query errors to Vue's error handler. + * A predicate receives the error and query and decides whether to throw. + * With `notifyOnChangeProps: 'none'`, errors are not sent to the Vue error handler. + * @defaultValue false + */ + throwOnError?: ThrowOnError +} + /** * `enabled` for Vue Query. A `ref` or `computed` is reactive, while a plain boolean isn't tracked on its own. A * zero-argument getter (`() => ...`) is reactive too: it is called while tracking dependencies. query-core's diff --git a/packages/vue-query/src/types.ts b/packages/vue-query/src/types.ts index d677cd0b006..4247400f557 100644 --- a/packages/vue-query/src/types.ts +++ b/packages/vue-query/src/types.ts @@ -6,7 +6,9 @@ import type { MutationCache, MutationObserverOptions, OmitKeyof, + Query, QueryCache, + QueryKey, } from '@tanstack/query-core' import type { ComputedRef, Ref, UnwrapRef } from 'vue' @@ -106,7 +108,14 @@ export type MutationOptions< MutationObserverOptions, '_defaulted' > & - ShallowOption + ShallowOption & { + /** + * Set to `true` to throw mutation errors to the nearest error boundary. + * A predicate receives the error and decides whether to throw. + * @defaultValue false + */ + throwOnError?: boolean | ((error: TError) => boolean) + } /** * The default options of a `QueryClient`, applied to every query (`queries`), mutation @@ -118,13 +127,15 @@ export interface DefaultOptions { * Default options applied to every query, unless overridden per-query. Also accepts the * `shallow` option. */ - queries?: CoreDefaultOptions['queries'] & ShallowOption + queries?: CoreDefaultOptions['queries'] & + ShallowOption & { + throwOnError?: ThrowOnError + } /** * Default options applied to every mutation, unless overridden per-mutation. Also accepts the * `shallow` option. */ - mutations?: MutationObserverOptions & - ShallowOption + mutations?: MutationOptions /** * Default options used when hydrating queries and mutations; see {@link HydrateOptions}. */ @@ -153,3 +164,16 @@ export interface QueryClientConfig { */ defaultOptions?: DefaultOptions } + +/** A boolean or predicate that sends query errors to the nearest error boundary. */ +export type ThrowOnError< + TQueryFnData, + TError, + TQueryData, + TQueryKey extends QueryKey, +> = + | boolean + | (( + error: TError, + query: Query, + ) => boolean) diff --git a/packages/vue-query/src/useBaseQuery.ts b/packages/vue-query/src/useBaseQuery.ts index 0a4a580e14d..8e30e58b29b 100644 --- a/packages/vue-query/src/useBaseQuery.ts +++ b/packages/vue-query/src/useBaseQuery.ts @@ -1,4 +1,3 @@ -import { shouldThrowError } from '@tanstack/query-core' import { computed, getCurrentScope, @@ -11,7 +10,7 @@ import { watch, } from 'vue' import { useQueryClient } from './useQueryClient' -import { cloneDeepUnref, updateState } from './utils' +import { cloneDeepUnref, shouldThrowError, updateState } from './utils' import type { DefaultedQueryObserverOptions, QueryKey, @@ -21,7 +20,7 @@ import type { import type { Ref } from 'vue' import type { QueryClient } from './queryClient' import type { UseQueryOptions } from './queryOptions' -import type { MaybeRefOrGetter } from './types' +import type { MaybeRefOrGetter, ShallowOption, ThrowOnError } from './types' import type { UseInfiniteQueryOptions } from './useInfiniteQuery' /** @@ -162,7 +161,10 @@ export function useBaseQuery< TData, TQueryData, TQueryKey - > = client.defaultQueryOptions(clonedOptions) + > & + ShallowOption & { + throwOnError?: ThrowOnError + } = client.defaultQueryOptions(clonedOptions) defaulted._optimisticResults = client.isRestoring?.value ? 'isRestoring' @@ -172,7 +174,6 @@ export function useBaseQuery< }) const observer = new Observer(client, defaultedOptions.value) - // @ts-expect-error const state = defaultedOptions.value.shallow ? shallowReactive(observer.getCurrentResult()) : reactive(observer.getCurrentResult()) @@ -277,6 +278,7 @@ export function useBaseQuery< if ( state.isError && !state.isFetching && + defaultedOptions.value.notifyOnChangeProps !== 'none' && shouldThrowError(defaultedOptions.value.throwOnError, [ error as TError, observer.getCurrentQuery(), @@ -287,7 +289,6 @@ export function useBaseQuery< }, ) - // @ts-expect-error const readonlyState = defaultedOptions.value.shallow ? shallowReadonly(state) : readonly(state) diff --git a/packages/vue-query/src/useInfiniteQuery.ts b/packages/vue-query/src/useInfiniteQuery.ts index a8dabafac09..6ed8d178e97 100644 --- a/packages/vue-query/src/useInfiniteQuery.ts +++ b/packages/vue-query/src/useInfiniteQuery.ts @@ -1,10 +1,10 @@ import { InfiniteQueryObserver } from '@tanstack/query-core' import { useBaseQuery } from './useBaseQuery' import type { + InfiniteQueryObserverOptions as CoreInfiniteQueryObserverOptions, DefaultError, DefinedInfiniteQueryObserverResult, InfiniteData, - InfiniteQueryObserverOptions, InfiniteQueryObserverResult, QueryKey, QueryObserver, @@ -21,9 +21,37 @@ import type { MaybeRefDeep, MaybeRefOrGetter, ShallowOption, + ThrowOnError, } from './types' import type { UseBaseQueryReturnType } from './useBaseQuery' +type InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey extends QueryKey, + TPageParam, +> = CoreInfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam +> & { + /** + * Set to `true` to send query errors to Vue's error handler. + * A predicate receives the error and query and decides whether to throw. + * With `notifyOnChangeProps: 'none'`, errors are not sent to the Vue error handler. + * @defaultValue false + */ + throwOnError?: ThrowOnError< + TQueryFnData, + TError, + InfiniteData, + TQueryKey + > +} + /** * The options accepted by `useInfiniteQuery`. Extends {@link InfiniteQueryObserverOptions} from * `@tanstack/query-core` with the `vue-query`-specific `shallow` option. Each option except `shallow` can also diff --git a/packages/vue-query/src/useMutation.ts b/packages/vue-query/src/useMutation.ts index 4c68d4ff0a3..368a91a369a 100644 --- a/packages/vue-query/src/useMutation.ts +++ b/packages/vue-query/src/useMutation.ts @@ -1,4 +1,4 @@ -import { MutationObserver, shouldThrowError } from '@tanstack/query-core' +import { MutationObserver } from '@tanstack/query-core' import { computed, getCurrentScope, @@ -11,7 +11,7 @@ import { watch, } from 'vue' import { useQueryClient } from './useQueryClient' -import { cloneDeepUnref, updateState } from './utils' +import { cloneDeepUnref, shouldThrowError, updateState } from './utils' import type { DefaultError, DistributiveOmit, diff --git a/packages/vue-query/src/useQueries.ts b/packages/vue-query/src/useQueries.ts index a5df7bb9ecb..9cb5a115a46 100644 --- a/packages/vue-query/src/useQueries.ts +++ b/packages/vue-query/src/useQueries.ts @@ -18,12 +18,16 @@ import type { QueryFunction, QueryKey, QueryObserverResult, - ThrowOnError, } from '@tanstack/query-core' import type { Ref } from 'vue' import type { QueryClient } from './queryClient' import type { UseQueryOptions } from './queryOptions' -import type { DeepUnwrapRef, MaybeRefDeep, ShallowOption } from './types' +import type { + DeepUnwrapRef, + MaybeRefDeep, + ShallowOption, + ThrowOnError, +} from './types' // This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`. // `placeholderData` function does not have a parameter diff --git a/packages/vue-query/src/utils.ts b/packages/vue-query/src/utils.ts index c87bc40eca2..e59690865a3 100644 --- a/packages/vue-query/src/utils.ts +++ b/packages/vue-query/src/utils.ts @@ -172,3 +172,20 @@ function isFunction(value: unknown): value is (...args: Array) => any { export function toValueDeep(source: (() => T) | MaybeRefDeep): T { return isFunction(source) ? source() : cloneDeepUnref(source) } + +/** + * Resolves the adapter's error boundary option. + * @param throwOnError - A boolean or a predicate. + * @param params - The arguments passed to the predicate. + * @returns Whether to throw the error. + */ +export function shouldThrowError) => boolean>( + throwOnError: boolean | T | undefined, + params: Parameters, +): boolean { + if (typeof throwOnError === 'function') { + return throwOnError(...params) + } + + return !!throwOnError +}