Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .changeset/adapter-error-boundary-options.md
Original file line number Diff line number Diff line change
@@ -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 whenever the result's error changes, even when `notifyOnChangeProps` is `'none'` or the component does not track `error`.
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
2 changes: 1 addition & 1 deletion packages/angular-query/src/__tests__/inject-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
14 changes: 6 additions & 8 deletions packages/angular-query/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,8 @@ type SignalFunction<T extends () => any> = T & Signal<ReturnType<T>>

/**
* 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
Expand All @@ -43,7 +42,7 @@ export type CreateQueryOptions<
TQueryKey extends QueryKey = QueryKey,
> = OmitKeyof<
QueryObserverOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>,
'notifyOnChangeProps' | 'suspense' | 'throwOnError'
'notifyOnChangeProps' | 'suspense'
>

type CreateStatusBasedQueryResult<
Expand Down Expand Up @@ -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
Expand All @@ -256,7 +254,7 @@ export interface CreateInfiniteQueryOptions<
TQueryKey,
TPageParam
>,
'notifyOnChangeProps' | 'suspense' | 'throwOnError'
'notifyOnChangeProps' | 'suspense'
> {}

/**
Expand Down Expand Up @@ -359,7 +357,7 @@ export interface CreateMutationOptions<
TOnMutateResult = unknown,
> extends OmitKeyof<
MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>,
'_defaulted' | 'throwOnError'
'_defaulted'
> {}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -589,7 +589,7 @@ describe('createQueriesController', () => {
queries: Array(50).map((_, i) => ({
queryKey: ['key', i] as const,
queryFn: () => i + 10,
throwOnError,
retry,
})),
},
new QueryClient(),
Expand Down Expand Up @@ -625,7 +625,7 @@ describe('createQueriesController', () => {
queryKey: ['key', i] as const,
queryFn: () => i + 10,
select: (data: number) => data.toString(),
throwOnError,
retry,
})),
},
new QueryClient(),
Expand Down Expand Up @@ -654,7 +654,7 @@ describe('createQueriesController', () => {
{
queryKey: key5,
queryFn: () => 'string',
throwOnError,
retry,
},
],
},
Expand All @@ -674,7 +674,7 @@ describe('createQueriesController', () => {
expectTypeOf(result3[3].data).toEqualTypeOf<string | undefined>()
// select takes precedence over queryFn
expectTypeOf(result3[2].data).toEqualTypeOf<number | undefined>()
// infer TError from throwOnError
// infer TError from retry
expectTypeOf(result3[3].error).toEqualTypeOf<BizError | null>()

// initialData/placeholderData are enforced
Expand All @@ -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(),
{
Expand Down Expand Up @@ -729,7 +729,7 @@ describe('createQueriesController', () => {
{
queryKey: key5,
queryFn: () => 'string',
throwOnError,
retry,
},
],
},
Expand Down Expand Up @@ -782,7 +782,7 @@ describe('createQueriesController', () => {
queryKey: key5,
queryFn: () => 'string',
select: (a: string) => parseInt(a),
throwOnError,
retry,
},
],
},
Expand Down Expand Up @@ -834,7 +834,7 @@ describe('createQueriesController', () => {
{
queryKey: key5,
queryFn: () => 'string',
throwOnError,
retry,
},
],
} as const,
Expand Down
11 changes: 8 additions & 3 deletions packages/lit-query/src/createQueriesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -63,7 +62,10 @@ type GetCreateQueriesInput<T> = T extends {
| QueryFunction<infer TQueryFnData, infer TQueryKey>
| SkipTokenForCreateQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
retry?:
| boolean
| number
| ((failureCount: number, error: infer TError) => boolean)
}
? CreateQueriesInputForController<
TQueryFnData,
Expand Down Expand Up @@ -114,7 +116,10 @@ type GetCreateQueriesResult<T> = T extends {
| QueryFunction<infer TQueryFnData, any>
| SkipTokenForCreateQueries
select?: (data: any) => infer TData
throwOnError?: ThrowOnError<any, infer TError, any, any>
retry?:
| boolean
| number
| ((failureCount: number, error: infer TError) => boolean)
}
? GetDefinedOrUndefinedCreateQueriesResult<
T,
Expand Down
88 changes: 88 additions & 0 deletions packages/preact-query/src/QueryClient.ts
Original file line number Diff line number Diff line change
@@ -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<TError> {
/** Default query options, including whether to throw errors to an error boundary. */
queries?: CoreDefaultOptions<TError>['queries'] &
Pick<UseBaseQueryOptions<unknown, TError>, 'throwOnError'>
/** Default mutation options, including whether to throw errors to an error boundary. */
mutations?: CoreDefaultOptions<TError>['mutations'] &
Pick<UseMutationOptions<unknown, TError, unknown>, '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<TQueryFnData, TError, TData, TQueryData>,
'queryKey' | 'subscribed'
>
>,
) => void

/** {@inheritDoc CoreQueryClient.getQueryDefaults} */
getQueryDefaults: (queryKey: QueryKey) => ReturnType<
CoreQueryClient['getQueryDefaults']
> & {
throwOnError?: ThrowOnError<any, any, any, any>
}

/** {@inheritDoc CoreQueryClient.setMutationDefaults} */
setMutationDefaults: <
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
>(
mutationKey: MutationKey,
options: Omit<
UseMutationOptions<TData, TError, TVariables, TOnMutateResult>,
'mutationKey'
>,
) => void

/** {@inheritDoc CoreQueryClient.getMutationDefaults} */
getMutationDefaults: (
mutationKey: MutationKey,
) => ReturnType<CoreQueryClient['getMutationDefaults']> &
Pick<UseMutationOptions<any, any, any, any>, 'throwOnError'>
}

/** Creates a query client. The constructor is shared with query-core. */
export const QueryClient: {
new (config?: QueryClientConfig): QueryClient
readonly prototype: QueryClient
} = CoreQueryClient
2 changes: 1 addition & 1 deletion packages/preact-query/src/QueryClientProvider.tsx
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
56 changes: 30 additions & 26 deletions packages/preact-query/src/__tests__/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2655,36 +2655,40 @@ 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([undefined, 'none'] as const)(
'sends query errors to the boundary with notifyOnChangeProps set to %s',
async (notifyOnChangeProps) => {
vi.spyOn(console, 'error').mockReturnValue(undefined)
const key = createKey()
queryClient.setQueryDefaults(key, { throwOnError: true })

function Page() {
const { status, error } = useQuery<unknown, string>({
queryKey: key,
queryFn: () => Promise.reject(new Error('Error test')),
retry: false,
throwOnError: true,
})
function Page() {
const { status, error } = useQuery<unknown, string>({
queryKey: key,
queryFn: () => Promise.reject(new Error('Error test')),
retry: false,
notifyOnChangeProps,
})

return (
<div>
<h1>{status}</h1>
<h2>{error}</h2>
</div>
)
}
return (
<div>
<h1>{status}</h1>
<h2>{error}</h2>
</div>
)
}

const rendered = renderWithClient(
queryClient,
<ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
<Page />
</ErrorBoundary>,
)
const rendered = renderWithClient(
queryClient,
<ErrorBoundary fallbackRender={() => <div>error boundary</div>}>
<Page />
</ErrorBoundary>,
)

await vi.advanceTimersByTimeAsync(0)
expect(rendered.getByText('error boundary')).toBeInTheDocument()
})
await vi.advanceTimersByTimeAsync(0)
expect(rendered.getByText('error boundary')).toBeInTheDocument()
},
)

it('should throw error if queryFn rejects with a falsy error and throwOnError is in use', async () => {
vi.spyOn(console, 'error').mockReturnValue(undefined)
Expand Down
Loading
Loading