-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Description
Describe the bug
useSuspenseQuery
ignores the staleTime
config parameter when it is a function instead of a number.
// staleTime number - ✅ works
useSuspenseQuery({
staleTime: Infinity,
// ...
})
// staleTime function - ❌ does not work: staleTime value defaults to a value of 1 second instead
useSuspenseQuery({
staleTime: () => Infinity,
// ...
})
Your minimal, reproducible example
https://codesandbox.io/p/github/afdca/tanstack-query-suspense-staletime/master
Steps to reproduce
- open the demo link, then open the Tanstack query devtools in the demo
- notice the staleTime function query goes stale after 1 second
- notice the staleTime number query never goes stale
- notice how both queries are set up in the code:
useSuspenseQuery({
queryFn: () => true,
queryKey: ["staleTime function"],
staleTime: () => Infinity, // Function
})
useSuspenseQuery({
queryFn: () => true,
queryKey: ["staleTime number"],
staleTime: Infinity, // Number
})
Expected behavior
useSuspenseQuery
should not ignore the staleTime
config parameter when it is a function.
How often does this bug happen?
Every time
Screenshots or Videos
No response
Platform
- OS - Windows 11
- Browser - Firefox 131.0.2 and Chrome 129.0.6668.100
- React - v18.3.1
Tanstack Query adapter
react-query
TanStack Query version
v5.59.12
TypeScript version
v5.6.3
Additional context
The issue seems to come from the ensureSuspenseTimers
function: https://github.com/TanStack/query/blob/main/packages/react-query/src/suspense.ts#L27
export const ensureSuspenseTimers = (
defaultedOptions: DefaultedQueryObserverOptions<any, any, any, any, any>,
) => {
if (defaultedOptions.suspense) {
// Always set stale time when using suspense to prevent
// fetching again when directly mounting after suspending
if (typeof defaultedOptions.staleTime !== 'number') { // ❗🚩Issue here
defaultedOptions.staleTime = 1000
}
if (typeof defaultedOptions.gcTime === 'number') {
defaultedOptions.gcTime = Math.max(defaultedOptions.gcTime, 1000)
}
}
}
The following fix should work:
if (typeof defaultedOptions.staleTime !== 'number' && typeof defaultedOptions.staleTime !== 'function') {
defaultedOptions.staleTime = 1000
}
TkDodo