Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
878ac34
test(react-query): add tests should retry on mount when throwOnError …
Han5991 Jun 30, 2025
3225745
fix(react-query): refine throwOnError retry logic for error boundary …
Han5991 Jun 30, 2025
4c40790
fix(react-query): enhance throwOnError logic in error boundaries
Han5991 Jun 30, 2025
182b239
test: Add tests for `throwOnError` behavior in `useQuery`
Han5991 Jul 6, 2025
e8e0caa
fix(react-query): improve throwOnError logic with query state validation
Han5991 Jul 6, 2025
4b795be
Merge branch 'main' into fix/usequery-retry-on-mount-with-throw-on-er…
Han5991 Sep 25, 2025
cd2dd84
Merge branch 'main' into fix/usequery-retry-on-mount-with-throw-on-er…
Han5991 Sep 26, 2025
435dd62
Merge branch 'main' into fix/usequery-retry-on-mount-with-throw-on-er…
Han5991 Oct 7, 2025
4a2dd73
Merge branch 'main' into fix/usequery-retry-on-mount-with-throw-on-er…
Han5991 Nov 9, 2025
199fc0a
fix(react-query): fix test flakiness and query cache timing (#9338)
Han5991 Nov 9, 2025
165e133
Merge branch 'main' into fix/usequery-retry-on-mount-with-throw-on-er…
TkDodo Dec 28, 2025
961219d
ci: apply automated fixes
autofix-ci[bot] Dec 28, 2025
9eea809
fix(react-query): refine retryOnMount logic and error boundary handling
Han5991 Dec 28, 2025
c422284
Merge branch 'main' into fix/usequery-retry-on-mount-with-throw-on-er…
TkDodo Dec 29, 2025
a22e583
ci: apply automated fixes
autofix-ci[bot] Dec 29, 2025
0892724
feat(react-query): make query param required but nullable in ensurePr…
Han5991 Dec 30, 2025
062c86d
Apply suggestions from code review
TkDodo Dec 30, 2025
75c1e69
chore: size-limit
TkDodo Dec 30, 2025
9fd84a6
chore: changeset
TkDodo Dec 30, 2025
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
5 changes: 5 additions & 0 deletions .changeset/long-ties-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/react-query': patch
---

fix(react-query): allow retryOnMount when throwOnError is function
4 changes: 2 additions & 2 deletions .size-limit.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
{
"name": "react full",
"path": "packages/react-query/build/modern/index.js",
"limit": "12.10 kB",
"limit": "12.13 kB",
"ignore": ["react", "react-dom"]
},
{
"name": "react minimal",
"path": "packages/react-query/build/modern/index.js",
"limit": "9.12 kB",
"limit": "9.15 kB",
"import": "{ useQuery, QueryClient, QueryClientProvider }",
"ignore": ["react", "react-dom"]
}
Expand Down
175 changes: 175 additions & 0 deletions packages/react-query/src/__tests__/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5921,6 +5921,7 @@ describe('useQuery', () => {
it('should be able to toggle subscribed', async () => {
const key = queryKey()
const queryFn = vi.fn(() => Promise.resolve('data'))

function Page() {
const [subscribed, setSubscribed] = React.useState(true)
const { data } = useQuery({
Expand Down Expand Up @@ -5965,6 +5966,7 @@ describe('useQuery', () => {
it('should not be attached to the query when subscribed is false', async () => {
const key = queryKey()
const queryFn = vi.fn(() => Promise.resolve('data'))

function Page() {
const { data } = useQuery({
queryKey: key,
Expand Down Expand Up @@ -5993,6 +5995,7 @@ describe('useQuery', () => {
it('should not re-render when data is added to the cache when subscribed is false', async () => {
const key = queryKey()
let renders = 0

function Page() {
const { data } = useQuery({
queryKey: key,
Expand Down Expand Up @@ -6192,6 +6195,7 @@ describe('useQuery', () => {
await sleep(5)
return { numbers: { current: { id } } }
}

function Test() {
const [id, setId] = React.useState(1)

Expand Down Expand Up @@ -6257,6 +6261,7 @@ describe('useQuery', () => {
await sleep(5)
return { numbers: { current: { id } } }
}

function Test() {
const [id, setId] = React.useState(1)

Expand Down Expand Up @@ -6762,10 +6767,12 @@ describe('useQuery', () => {
it('should console.error when there is no queryFn', () => {
const consoleErrorMock = vi.spyOn(console, 'error')
const key = queryKey()

function Example() {
useQuery({ queryKey: key })
return <></>
}

renderWithClient(queryClient, <Example />)

expect(consoleErrorMock).toHaveBeenCalledTimes(1)
Expand All @@ -6775,4 +6782,172 @@ describe('useQuery', () => {

consoleErrorMock.mockRestore()
})

it('should retry on mount when throwOnError returns false', async () => {
const key = queryKey()
let fetchCount = 0
const queryFn = vi.fn().mockImplementation(() => {
fetchCount++
console.log(`Fetching... (attempt ${fetchCount})`)
return Promise.reject(new Error('Simulated 500 error'))
})

function Component() {
const { status, error } = useQuery({
queryKey: key,
queryFn,
throwOnError: () => false,
retryOnMount: true,
staleTime: Infinity,
retry: false,
})

return (
<div>
<div data-testid="status">{status}</div>
{error && <div data-testid="error">{error.message}</div>}
</div>
)
}

const rendered1 = renderWithClient(queryClient, <Component />)
await vi.advanceTimersByTimeAsync(0)
expect(rendered1.getByTestId('status')).toHaveTextContent('error')
expect(rendered1.getByTestId('error')).toHaveTextContent(
'Simulated 500 error',
)
expect(fetchCount).toBe(1)
rendered1.unmount()

const initialFetchCount = fetchCount

const rendered2 = renderWithClient(queryClient, <Component />)
await vi.advanceTimersByTimeAsync(0)
expect(rendered2.getByTestId('status')).toHaveTextContent('error')

expect(fetchCount).toBe(initialFetchCount + 1)
expect(queryFn).toHaveBeenCalledTimes(2)
})

it('should not retry on mount when throwOnError function returns true', async () => {
const key = queryKey()
let fetchCount = 0
const queryFn = vi.fn().mockImplementation(() => {
fetchCount++
console.log(`Fetching... (attempt ${fetchCount})`)
return Promise.reject(new Error('Simulated 500 error'))
})

function Component() {
const { status, error } = useQuery({
queryKey: key,
queryFn,
throwOnError: () => true,
retryOnMount: true,
staleTime: Infinity,
retry: false,
})

return (
<div>
<div data-testid="status">{status}</div>
{error && <div data-testid="error">{error.message}</div>}
</div>
)
}

const rendered1 = renderWithClient(
queryClient,
<ErrorBoundary
fallbackRender={({ error }) => (
<div>
<div data-testid="status">error</div>
<div data-testid="error">{error?.message}</div>
</div>
)}
>
<Component />
</ErrorBoundary>,
)
await vi.advanceTimersByTimeAsync(0)
expect(rendered1.getByTestId('status')).toHaveTextContent('error')
expect(rendered1.getByTestId('error')).toHaveTextContent(
'Simulated 500 error',
)
expect(fetchCount).toBe(1)

rendered1.unmount()

const initialFetchCount = fetchCount

const rendered2 = renderWithClient(
queryClient,
<ErrorBoundary
fallbackRender={({ error }) => (
<div>
<div data-testid="status">error</div>
<div data-testid="error">{error?.message}</div>
</div>
)}
>
<Component />
</ErrorBoundary>,
)
await vi.advanceTimersByTimeAsync(0)
expect(rendered2.getByTestId('status')).toHaveTextContent('error')

// Should not retry because throwOnError returns true
expect(fetchCount).toBe(initialFetchCount)
expect(queryFn).toHaveBeenCalledTimes(1)
})

it('should handle throwOnError function based on actual error state', async () => {
const key = queryKey()
let fetchCount = 0
const queryFn = vi.fn().mockImplementation(() => {
fetchCount++
console.log(`Fetching... (attempt ${fetchCount})`)
return Promise.reject(new Error('Simulated 500 error'))
})

function Component() {
const { status, error } = useQuery({
queryKey: key,
queryFn,
throwOnError: (error) => error.message.includes('404'),
retryOnMount: true,
staleTime: Infinity,
retry: false,
})

return (
<div>
<div data-testid="status">{status}</div>
{error && <div data-testid="error">{error.message}</div>}
</div>
)
}

const rendered1 = renderWithClient(queryClient, <Component />)

await vi.advanceTimersByTimeAsync(0)
expect(rendered1.getByTestId('status')).toHaveTextContent('error')
expect(rendered1.getByTestId('error')).toHaveTextContent(
'Simulated 500 error',
)
expect(fetchCount).toBe(1)

rendered1.unmount()

const initialFetchCount = fetchCount

const rendered2 = renderWithClient(queryClient, <Component />)

await vi.advanceTimersByTimeAsync(0)
expect(rendered2.getByTestId('status')).toHaveTextContent('error')

// Should retry because throwOnError returns false (500 error doesn't include '404')
expect(fetchCount).toBe(initialFetchCount + 1)
expect(queryFn).toHaveBeenCalledTimes(2)
})
})
10 changes: 8 additions & 2 deletions packages/react-query/src/errorBoundaryUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,17 @@ export const ensurePreventErrorBoundaryRetry = <
TQueryKey
>,
errorResetBoundary: QueryErrorResetBoundaryValue,
query: Query<TQueryFnData, TError, TQueryData, TQueryKey> | undefined,
) => {
const throwOnError =
query?.state.error && typeof options.throwOnError === 'function'
? shouldThrowError(options.throwOnError, [query.state.error, query])
: options.throwOnError

if (
options.suspense ||
options.throwOnError ||
options.experimental_prefetchInRender
options.experimental_prefetchInRender ||
throwOnError
) {
// Prevent retrying failed query if the error boundary has not been reset yet
if (!errorResetBoundary.isReset()) {
Expand Down
24 changes: 12 additions & 12 deletions packages/react-query/src/useBaseQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,19 @@ export function useBaseQuery<
const errorResetBoundary = useQueryErrorResetBoundary()
const client = useQueryClient(queryClient)
const defaultedOptions = client.defaultQueryOptions(options)

;(client.getDefaultOptions().queries as any)?._experimental_beforeQuery?.(
defaultedOptions,
)

const query = client
.getQueryCache()
.get<
TQueryFnData,
TError,
TQueryData,
TQueryKey
>(defaultedOptions.queryHash)

if (process.env.NODE_ENV !== 'production') {
if (!defaultedOptions.queryFn) {
console.error(
Expand All @@ -72,8 +80,7 @@ export function useBaseQuery<
: 'optimistic'

ensureSuspenseTimers(defaultedOptions)
ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary)

ensurePreventErrorBoundaryRetry(defaultedOptions, errorResetBoundary, query)
useClearResetErrorBoundary(errorResetBoundary)

// this needs to be invoked before creating the Observer because that can create a cache entry
Expand Down Expand Up @@ -127,14 +134,7 @@ export function useBaseQuery<
result,
errorResetBoundary,
throwOnError: defaultedOptions.throwOnError,
query: client
.getQueryCache()
.get<
TQueryFnData,
TError,
TQueryData,
TQueryKey
>(defaultedOptions.queryHash),
query,
suspense: defaultedOptions.suspense,
})
) {
Expand All @@ -155,7 +155,7 @@ export function useBaseQuery<
? // Fetch immediately on render in order to ensure `.promise` is resolved even if the component is unmounted
fetchOptimistic(defaultedOptions, observer, errorResetBoundary)
: // subscribe to the "cache promise" so that we can finalize the currentThenable once data comes in
client.getQueryCache().get(defaultedOptions.queryHash)?.promise
query?.promise

promise?.catch(noop).finally(() => {
// `.updateResult()` will trigger `.#currentThenable` to finalize
Expand Down
7 changes: 4 additions & 3 deletions packages/react-query/src/useQueries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,9 +242,10 @@ export function useQueries<
[queries, client, isRestoring],
)

defaultedQueries.forEach((query) => {
ensureSuspenseTimers(query)
ensurePreventErrorBoundaryRetry(query, errorResetBoundary)
defaultedQueries.forEach((queryOptions) => {
ensureSuspenseTimers(queryOptions)
const query = client.getQueryCache().get(queryOptions.queryHash)
ensurePreventErrorBoundaryRetry(queryOptions, errorResetBoundary, query)
})

useClearResetErrorBoundary(errorResetBoundary)
Expand Down
Loading