Skip to content

Commit

Permalink
fix(react-query): do not overwrite staleTime with the suspense defaul…
Browse files Browse the repository at this point in the history
…t value if it's a function (#8174)

* fix(react-query): do not overwrite staleTime with the suspense default value if it's a function

* test: improve

* chore: fix test
  • Loading branch information
TkDodo authored Oct 13, 2024
1 parent 2649e52 commit d409854
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
40 changes: 40 additions & 0 deletions packages/react-query/src/__tests__/suspense.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,46 @@ describe('useSuspenseQuery', () => {
await waitFor(() => rendered.getByText('fetching: false'))
})

it('should set staleTime when having passed a function', async () => {
const key = queryKey()
let count = 0

function Component() {
const result = useSuspenseQuery({
queryKey: key,
queryFn: async () => {
await sleep(5)
count++
return count
},
staleTime: () => 60 * 1000,
})
return (
<div>
<span>data: {result.data}</span>
</div>
)
}

function Page() {
return (
<React.Suspense fallback="Loading...">
<Component />
</React.Suspense>
)
}

const rendered = renderWithClient(queryClient, <Page />)

await waitFor(() => rendered.getByText('Loading...'))
await waitFor(() => rendered.getByText('data: 1'))

expect(
typeof queryClient.getQueryCache().find({ queryKey: key })?.observers[0]
?.options.staleTime,
).toBe('function')
})

it('should suspend when switching to a new query', async () => {
const key1 = queryKey()
const key2 = queryKey()
Expand Down
2 changes: 1 addition & 1 deletion packages/react-query/src/suspense.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const ensureSuspenseTimers = (
if (defaultedOptions.suspense) {
// Always set stale time when using suspense to prevent
// fetching again when directly mounting after suspending
if (typeof defaultedOptions.staleTime !== 'number') {
if (defaultedOptions.staleTime === undefined) {
defaultedOptions.staleTime = 1000
}
if (typeof defaultedOptions.gcTime === 'number') {
Expand Down

0 comments on commit d409854

Please sign in to comment.