Skip to content

Commit 0aafb42

Browse files
authored
fix(query): make sure prefetched queries can be garbage collected (TanStack#3007)
1 parent 27e72de commit 0aafb42

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/core/query.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,11 @@ export class Query<
163163
private observers: QueryObserver<any, any, any, any, any>[]
164164
private defaultOptions?: QueryOptions<TQueryFnData, TError, TData, TQueryKey>
165165
private abortSignalConsumed: boolean
166+
private hadObservers: boolean
166167

167168
constructor(config: QueryConfig<TQueryFnData, TError, TData, TQueryKey>) {
168169
this.abortSignalConsumed = false
170+
this.hadObservers = false
169171
this.defaultOptions = config.defaultOptions
170172
this.setOptions(config.options)
171173
this.observers = []
@@ -175,6 +177,7 @@ export class Query<
175177
this.initialState = config.state || this.getDefaultState(this.options)
176178
this.state = this.initialState
177179
this.meta = config.meta
180+
this.scheduleGc()
178181
}
179182

180183
private setOptions(
@@ -215,7 +218,9 @@ export class Query<
215218
private optionalRemove() {
216219
if (!this.observers.length) {
217220
if (this.state.isFetching) {
218-
this.scheduleGc()
221+
if (this.hadObservers) {
222+
this.scheduleGc()
223+
}
219224
} else {
220225
this.cache.remove(this)
221226
}
@@ -321,6 +326,7 @@ export class Query<
321326
addObserver(observer: QueryObserver<any, any, any, any, any>): void {
322327
if (this.observers.indexOf(observer) === -1) {
323328
this.observers.push(observer)
329+
this.hadObservers = true
324330

325331
// Stop the query from being garbage collected
326332
this.clearGcTimeout()

src/core/tests/queryClient.test.tsx

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,21 @@ describe('queryClient', () => {
544544

545545
consoleMock.mockRestore()
546546
})
547+
548+
test('should be garbage collected after cacheTime if unused', async () => {
549+
const key = queryKey()
550+
551+
await queryClient.prefetchQuery(
552+
key,
553+
async () => {
554+
return 'data'
555+
},
556+
{ cacheTime: 10 }
557+
)
558+
expect(queryCache.find(key)).toBeDefined()
559+
await sleep(15)
560+
expect(queryCache.find(key)).not.toBeDefined()
561+
})
547562
})
548563

549564
describe('removeQueries', () => {

0 commit comments

Comments
 (0)