diff --git a/.changeset/adapter-error-boundary-options.md b/.changeset/adapter-error-boundary-options.md new file mode 100644 index 00000000000..db033da2142 --- /dev/null +++ b/.changeset/adapter-error-boundary-options.md @@ -0,0 +1,14 @@ +--- +'@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. 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/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..3eec7efd8e0 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` and `suspense`. 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' | 'suspense' > 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` and `suspense`, 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' | 'suspense' > {} /** @@ -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 ff9f24683cd..958d45e332f 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__/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..bc3d79107c3 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`), @@ -17,14 +12,14 @@ import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. * @param query - The query, used to evaluate a `throwOnError` function against its error. */ -export const ensurePreventErrorBoundaryRetry = < +export const prepareErrorBoundaryOptions = < TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, >( - options: DefaultedQueryObserverOptions< + options: DefaultedQueryOptions< TQueryFnData, TError, TData, @@ -34,6 +29,10 @@ export const ensurePreventErrorBoundaryRetry = < errorResetBoundary: QueryErrorResetBoundaryValue, query: Query | undefined, ) => { + if (options.notifyOnChangeProps === 'none') { + options.throwOnError = false + } + const throwOnError = query?.state.status === 'error' && typeof options.throwOnError === 'function' @@ -87,7 +86,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/types.ts b/packages/preact-query/src/types.ts index 2c12ae34fbc..66a3b8577f8 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 @@ -217,8 +259,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 +273,24 @@ export interface UseInfiniteQueryOptions< TData = InfiniteData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> extends OmitKeyof< - InfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - 'suspense' -> { +> + extends + OmitKeyof< + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'suspense' + >, + 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..fcfe67fa566 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, suspense: !!suspense }) const query = client .getQueryCache() @@ -90,7 +93,7 @@ export function useBaseQuery< : undefined suspense?.prepare(defaultedOptions) - ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions(defaultedOptions, errorResetBoundary, query) useClearResetErrorBoundary(errorResetBoundary) 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..e62c7b4c898 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,12 @@ import type { QueryClient, QueryFunction, QueryKey, - QueryObserverOptions, - ThrowOnError, } from '@tanstack/query-core' import type { suspenseQueriesPolicy } from './suspense' import type { + DefaultedQueryOptions, DefinedUseQueryResult, + ThrowOnError, UseQueryOptions, UseQueryResult, } from './types' @@ -348,10 +348,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, suspense: !!suspense }) // Make sure the results are already in fetching state before subscribing or updating options defaultedOptions._optimisticResults = isRestoring @@ -368,24 +366,23 @@ export function useBaseQueries< defaultedQueries.forEach((queryOptions) => { suspense?.prepare(queryOptions) const query = client.getQueryCache().get(queryOptions.queryHash) - ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions(queryOptions, errorResetBoundary, query) }) useClearResetErrorBoundary(errorResetBoundary) + const observerOptions = options as QueriesObserverOptions + const [observer] = useState( () => new QueriesObserver( client, defaultedQueries, - options as QueriesObserverOptions, + observerOptions, ), ) - const reader = observer.createResultReader( - defaultedQueries, - options as QueriesObserverOptions, - ) + const reader = observer.createResultReader(defaultedQueries, observerOptions) suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) // Commit the combine cache before subscription can start a fetch. 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__/queryObserver.test-d.tsx b/packages/query-core/src/__tests__/queryObserver.test-d.tsx index 8049ce4ce16..faa87ca2772 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, { @@ -1465,14 +1427,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 9ce8de6ce59..a16928acb21 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..558dd3f132b 100644 --- a/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx +++ b/packages/query-core/src/__tests__/queryObserverResultReader.test.tsx @@ -408,7 +408,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 1faad148309..6257694d3cc 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, sleep, timeUntilStale, @@ -778,46 +777,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('sleep', () => { it('should return a Promise', () => { expectTypeOf(sleep(1)).toEqualTypeOf>() 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/queryClient.ts b/packages/query-core/src/queryClient.ts index 98b4771382c..6c8a28b6575 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`, `suspense`, 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 a76cfc492d8..5297298e7e0 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -925,24 +925,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 diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 113b83210cb..8ea52edd439 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -505,19 +505,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 @@ -614,20 +601,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. @@ -636,12 +615,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. @@ -655,6 +628,9 @@ export interface QueryObserverOptionsBase< TQueryKey > + /** Set to `true` to use Suspense fetch behavior. */ + suspense?: boolean + /** @internal */ _optimisticResults?: 'optimistic' | 'isRestoring' } @@ -693,7 +669,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, @@ -711,7 +687,7 @@ export type DefaultedQueryObserverOptions< TQueryKey, TPageParam >, - 'throwOnError' | 'refetchOnReconnect' | 'queryHash' + 'refetchOnReconnect' | 'queryHash' > /** @@ -738,7 +714,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, @@ -1946,23 +1922,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 diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 7f39a202c20..854fceb7124 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -737,36 +737,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__/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..f7e2d9efcbf 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`), @@ -18,14 +13,14 @@ import type { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary' * @param errorResetBoundary - The value of the nearest `QueryErrorResetBoundary`. * @param query - The query, used to evaluate a `throwOnError` function against its error. */ -export const ensurePreventErrorBoundaryRetry = < +export const prepareErrorBoundaryOptions = < TQueryFnData, TError, TData, TQueryData, TQueryKey extends QueryKey, >( - options: DefaultedQueryObserverOptions< + options: DefaultedQueryOptions< TQueryFnData, TError, TData, @@ -35,6 +30,10 @@ export const ensurePreventErrorBoundaryRetry = < errorResetBoundary: QueryErrorResetBoundaryValue, query: Query | undefined, ) => { + if (options.notifyOnChangeProps === 'none') { + options.throwOnError = false + } + const throwOnError = query?.state.status === 'error' && typeof options.throwOnError === 'function' @@ -88,7 +87,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/types.ts b/packages/react-query/src/types.ts index 269b7955b41..3f5cd19686b 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 @@ -218,8 +260,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 +274,24 @@ export interface UseInfiniteQueryOptions< TData = InfiniteData, TQueryKey extends QueryKey = QueryKey, TPageParam = unknown, -> extends OmitKeyof< - InfiniteQueryObserverOptions< - TQueryFnData, - TError, - TData, - TQueryKey, - TPageParam - >, - 'suspense' -> { +> + extends + OmitKeyof< + InfiniteQueryObserverOptions< + TQueryFnData, + TError, + TData, + TQueryKey, + TPageParam + >, + 'suspense' + >, + 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..452e95b5023 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, suspense: !!suspense }) const query = client .getQueryCache() @@ -90,7 +93,7 @@ export function useBaseQuery< : undefined suspense?.prepare(defaultedOptions) - ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions(defaultedOptions, errorResetBoundary, query) useClearResetErrorBoundary(errorResetBoundary) const [observer] = React.useState( 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..a63e544d5fd 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,12 @@ import type { QueryClient, QueryFunction, QueryKey, - QueryObserverOptions, - ThrowOnError, } from '@tanstack/query-core' import type { suspenseQueriesPolicy } from './suspense' import type { + DefaultedQueryOptions, DefinedUseQueryResult, + ThrowOnError, UseQueryOptions, UseQueryResult, } from './types' @@ -400,10 +400,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, suspense: !!suspense }) // Make sure the results are already in fetching state before subscribing or updating options defaultedOptions._optimisticResults = isRestoring @@ -420,24 +418,23 @@ export function useBaseQueries< defaultedQueries.forEach((queryOptions) => { suspense?.prepare(queryOptions) const query = client.getQueryCache().get(queryOptions.queryHash) - ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query) + prepareErrorBoundaryOptions(queryOptions, errorResetBoundary, query) }) useClearResetErrorBoundary(errorResetBoundary) + const observerOptions = options as QueriesObserverOptions + const [observer] = React.useState( () => new QueriesObserver( client, defaultedQueries, - options as QueriesObserverOptions, + observerOptions, ), ) - const reader = observer.createResultReader( - defaultedQueries, - options as QueriesObserverOptions, - ) + const reader = observer.createResultReader(defaultedQueries, observerOptions) suspense?.readQueries(defaultedQueries, reader, client, errorResetBoundary) // Commit the combine cache before subscription can start a fetch. 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..d5f9f0bf75c 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. @@ -37,6 +40,12 @@ export interface QueryObserverOptions< >, 'structuralSharing' | 'suspense' > { + /** + * 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. @@ -73,6 +82,18 @@ export interface InfiniteQueryObserverOptions< >, 'structuralSharing' | 'suspense' > { + /** + * 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 +}