Skip to content

Error boundary handling for useQueries #4177

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Sep 24, 2022
Merged
Show file tree
Hide file tree
Changes from 6 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
2 changes: 2 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@
"avatar_url": "https://avatars0.githubusercontent.com/u/5398733?v=4",
"profile": "https://github.com/zorzysty",
"contributions": [
"bug",
"code",
"doc"
]
},
Expand Down
4 changes: 4 additions & 0 deletions packages/query-core/src/queriesObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,10 @@ export class QueriesObserver extends Subscribable<QueriesObserverListener> {
return this.result
}

getQueries() {
return this.observers.map((observer) => observer.getCurrentQuery())
}

getOptimisticResult(queries: QueryObserverOptions[]): QueryObserverResult[] {
return this.findMatchingObservers(queries).map((match) =>
match.observer.getOptimisticResult(match.defaultedQueryOptions),
Expand Down
2 changes: 1 addition & 1 deletion packages/react-query/src/QueryErrorResetBoundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import * as React from 'react'

// CONTEXT

interface QueryErrorResetBoundaryValue {
export interface QueryErrorResetBoundaryValue {
clearReset: () => void
isReset: () => boolean
reset: () => void
Expand Down
50 changes: 50 additions & 0 deletions packages/react-query/src/__tests__/useQueries.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1104,4 +1104,54 @@ describe('useQueries', () => {
await waitFor(() => rendered.getByText('error boundary'))
})
})

it("should throw error if in one of queries' queryFn throws and useErrorBoundary is in use", async () => {
const key1 = queryKey()
const key2 = queryKey()
const key3 = queryKey()

function Page() {
useQueries({
queries: [
{
queryKey: key1,
queryFn: () =>
Promise.reject(
'this should not throw because useErrorBoundary is not set',
),
},
{
queryKey: key2,
queryFn: () => Promise.reject('single query error'),
useErrorBoundary: true,
retry: false,
},
{
queryKey: key3,
queryFn: async () => 2,
},
],
})

return null
}

const rendered = renderWithClient(
queryClient,
<ErrorBoundary
fallbackRender={({ error }) => (
<div>
<div>error boundary</div>
{/* @ts-expect-error `error` here is actually of type `string` and not `Error` */}
<div>{error}</div>
</div>
)}
>
<Page />
</ErrorBoundary>,
)

await waitFor(() => rendered.getByText('error boundary'))
await waitFor(() => rendered.getByText('single query error'))
})
})
2 changes: 2 additions & 0 deletions packages/react-query/src/__tests__/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2808,6 +2808,8 @@ describe('useQuery', () => {

await sleep(10)

await waitFor(() => expect(queryClient.isFetching()).toBe(0))

expect(result?.data).toBe('data')
})

Expand Down
67 changes: 67 additions & 0 deletions packages/react-query/src/errorBoundaryUtils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {
DefaultedQueryObserverOptions,
Query,
QueryKey,
QueryObserverResult,
} from '@tanstack/query-core'
import { QueryErrorResetBoundaryValue } from './QueryErrorResetBoundary'
import * as React from 'react'
import { shouldThrowError } from './utils'

export const ensurePreventErrorBoundaryRetry = <
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey extends QueryKey,
>(
options: DefaultedQueryObserverOptions<
TQueryFnData,
TError,
TData,
TQueryData,
TQueryKey
>,
errorResetBoundary: QueryErrorResetBoundaryValue,
) => {
if (options.suspense || options.useErrorBoundary) {
// Prevent retrying failed query if the error boundary has not been reset yet
if (!errorResetBoundary.isReset()) {
options.retryOnMount = false
}
}
}

export const useClearResetErrorBoundary = (
errorResetBoundary: QueryErrorResetBoundaryValue,
) => {
React.useEffect(() => {
errorResetBoundary.clearReset()
}, [errorResetBoundary])
}

export const getHasError = <
TData,
TError,
TQueryFnData,
TQueryData,
TQueryKey extends QueryKey,
TUseErrorBoundaryFn extends (...args: any[]) => boolean,
>({
result,
errorResetBoundary,
useErrorBoundary,
query,
}: {
result: QueryObserverResult<TData, TError>
errorResetBoundary: QueryErrorResetBoundaryValue
useErrorBoundary: boolean | TUseErrorBoundaryFn | undefined
query: Query<TQueryFnData, TError, TQueryData, TQueryKey>
}) => {
return (
result.isError &&
!errorResetBoundary.isReset() &&
!result.isFetching &&
shouldThrowError(useErrorBoundary, [result.error, query] as Parameters<TUseErrorBoundaryFn>)
)
}
34 changes: 15 additions & 19 deletions packages/react-query/src/useBaseQuery.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import * as React from 'react'
import { useSyncExternalStore } from './useSyncExternalStore'

import { QueryKey, notifyManager, QueryObserver } from '@tanstack/query-core'
import { notifyManager, QueryKey, QueryObserver } from '@tanstack/query-core'
import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
import { useQueryClient } from './QueryClientProvider'
import { UseBaseQueryOptions } from './types'
import { shouldThrowError } from './utils'
import { useIsRestoring } from './isRestoring'
import {
ensurePreventErrorBoundaryRetry,
getHasError,
useClearResetErrorBoundary,
} from './errorBoundaryUtils'

export function useBaseQuery<
TQueryFnData,
Expand Down Expand Up @@ -61,12 +65,9 @@ export function useBaseQuery<
}
}

if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {
// Prevent retrying failed query if the error boundary has not been reset yet
if (!errorResetBoundary.isReset()) {
defaultedOptions.retryOnMount = false
}
}
ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary)

useClearResetErrorBoundary(errorResetBoundary)

const [observer] = React.useState(
() =>
Expand All @@ -90,10 +91,6 @@ export function useBaseQuery<
() => observer.getCurrentResult(),
)

React.useEffect(() => {
errorResetBoundary.clearReset()
}, [errorResetBoundary])

React.useEffect(() => {
// Do not notify on updates because of changes in the options because
// these changes should already be reflected in the optimistic result.
Expand Down Expand Up @@ -122,13 +119,12 @@ export function useBaseQuery<

// Handle error boundary
if (
result.isError &&
!errorResetBoundary.isReset() &&
!result.isFetching &&
shouldThrowError(defaultedOptions.useErrorBoundary, [
result.error,
observer.getCurrentQuery(),
])
getHasError({
result,
errorResetBoundary,
useErrorBoundary: defaultedOptions.useErrorBoundary,
query: observer.getCurrentQuery(),
})
) {
throw result.error
}
Expand Down
32 changes: 30 additions & 2 deletions packages/react-query/src/useQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@ import * as React from 'react'
import { useSyncExternalStore } from './useSyncExternalStore'

import {
QueryKey,
QueryFunction,
notifyManager,
QueriesObserver,
QueryFunction,
QueryKey,
} from '@tanstack/query-core'
import { useQueryClient } from './QueryClientProvider'
import { UseQueryOptions, UseQueryResult } from './types'
import { useIsRestoring } from './isRestoring'
import { useQueryErrorResetBoundary } from './QueryErrorResetBoundary'
import {
ensurePreventErrorBoundaryRetry,
getHasError,
useClearResetErrorBoundary,
} from './errorBoundaryUtils'

// This defines the `UseQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
// - `context` is omitted as it is passed as a root-level option to `useQueries` instead.
Expand Down Expand Up @@ -188,5 +194,27 @@ export function useQueries<T extends any[]>({
observer.setQueries(defaultedQueries, { listeners: false })
}, [defaultedQueries, observer])

const errorResetBoundary = useQueryErrorResetBoundary()

defaultedQueries.forEach((options) => {
ensurePreventErrorBoundaryRetry(options, errorResetBoundary)
})

useClearResetErrorBoundary(errorResetBoundary)

const firstSingleResultWhichShouldThrow = result.find(
(singleResult, index) =>
getHasError({
result: singleResult,
errorResetBoundary,
useErrorBoundary: defaultedQueries[index]?.useErrorBoundary ?? false,
query: observer.getQueries()[index]!,
}),
)

if (firstSingleResultWhichShouldThrow?.error) {
throw firstSingleResultWhichShouldThrow.error
}

return result as QueriesResults<T>
}