Skip to content

Commit 8b57710

Browse files
committed
fix: remove query immediately if cacheTime is 0
1 parent 3545362 commit 8b57710

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

src/core/query.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,9 +164,13 @@ export class Query<TData = unknown, TError = unknown, TQueryFnData = TData> {
164164
this.clearGcTimeout()
165165

166166
if (!this.observers.length && isValidTimeout(this.cacheTime)) {
167-
this.gcTimeout = setTimeout(() => {
167+
if (!this.cacheTime) {
168168
this.cache.remove(this)
169-
}, this.cacheTime)
169+
} else {
170+
this.gcTimeout = setTimeout(() => {
171+
this.cache.remove(this)
172+
}, this.cacheTime)
173+
}
170174
}
171175
}
172176

src/core/tests/queryCache.test.tsx

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,9 +1009,8 @@ describe('queryCache', () => {
10091009
})
10101010
expect(queryCache.find(key)).toBeDefined()
10111011
const unsubscribe = observer.subscribe()
1012-
unsubscribe()
10131012
expect(queryCache.find(key)).toBeDefined()
1014-
await sleep(100)
1013+
unsubscribe()
10151014
expect(queryCache.find(key)).toBeUndefined()
10161015
})
10171016

@@ -1411,6 +1410,31 @@ describe('queryCache', () => {
14111410

14121411
consoleMock.mockRestore()
14131412
})
1413+
1414+
test('queries with cacheTime 0 should be removed immediately after unsubscribing', async () => {
1415+
const consoleMock = mockConsoleError()
1416+
const key = queryKey()
1417+
const testClient = new QueryClient()
1418+
let count = 0
1419+
const observer = new QueryObserver(testClient, {
1420+
queryKey: key,
1421+
queryFn: () => {
1422+
count++
1423+
return 'data'
1424+
},
1425+
cacheTime: 0,
1426+
staleTime: Infinity,
1427+
})
1428+
const unsubscribe1 = observer.subscribe()
1429+
unsubscribe1()
1430+
await sleep(10)
1431+
const unsubscribe2 = observer.subscribe()
1432+
unsubscribe2()
1433+
await sleep(10)
1434+
expect(count).toBe(2)
1435+
testClient.clear()
1436+
consoleMock.mockRestore()
1437+
})
14141438
})
14151439

14161440
describe('QueryObserver', () => {

0 commit comments

Comments
 (0)