Skip to content

Commit 2771a15

Browse files
authored
fix(useBaseQuery): set cacheTime to 1 in Suspense mode when cacheTime is set to 0 (#2821)
1 parent 05a8057 commit 2771a15

File tree

3 files changed

+55
-0
lines changed

3 files changed

+55
-0
lines changed

docs/src/pages/guides/testing.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,10 @@ setLogger({
8585
})
8686
```
8787

88+
## Set cacheTime to Infinity with Jest
89+
90+
`cacheTime` is set to 5 minutes by default. It means that the cache garbage collector timer will be triggered every 5 minutes. If you use Jest, you can set the `cacheTime` to `Infinity` to prevent "Jest did not exit one second after the test run completed" error message.
91+
8892
## Testing Network Calls
8993

9094
The primary use for React Query is to cache network requests, so it's important that we can test our code is making the correct network requests in the first place.

src/react/tests/suspense.test.tsx

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -890,4 +890,49 @@ describe("useQuery's in Suspense mode", () => {
890890
await waitFor(() => rendered.getByText('error boundary'))
891891
consoleMock.mockRestore()
892892
})
893+
894+
it('should render the correct amount of times in Suspense mode when cacheTime is set to 0', async () => {
895+
const key = queryKey()
896+
let state: UseQueryResult<number> | null = null
897+
898+
let count = 0
899+
let renders = 0
900+
901+
function Page() {
902+
renders++
903+
904+
state = useQuery(
905+
key,
906+
async () => {
907+
count++
908+
await sleep(10)
909+
return count
910+
},
911+
{ suspense: true, cacheTime: 0 }
912+
)
913+
914+
return (
915+
<div>
916+
<span>rendered</span>
917+
</div>
918+
)
919+
}
920+
921+
const rendered = renderWithClient(
922+
queryClient,
923+
<React.Suspense fallback="loading">
924+
<Page />
925+
</React.Suspense>
926+
)
927+
928+
await waitFor(() =>
929+
expect(state).toMatchObject({
930+
data: 1,
931+
status: 'success',
932+
})
933+
)
934+
935+
expect(renders).toBe(2)
936+
expect(rendered.queryByText('rendered')).not.toBeNull()
937+
})
893938
})

src/react/useBaseQuery.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ export function useBaseQuery<
5959
if (typeof defaultedOptions.staleTime !== 'number') {
6060
defaultedOptions.staleTime = 1000
6161
}
62+
63+
// Set cache time to 1 if the option has been set to 0
64+
// when using suspense to prevent infinite loop of fetches
65+
if (defaultedOptions.cacheTime === 0) {
66+
defaultedOptions.cacheTime = 1
67+
}
6268
}
6369

6470
if (defaultedOptions.suspense || defaultedOptions.useErrorBoundary) {

0 commit comments

Comments
 (0)