Skip to content

Commit 8a28904

Browse files
authored
fix(query-core): ignore stale query removals (#11524)
1 parent fcd8b5b commit 8a28904

3 files changed

Lines changed: 12 additions & 7 deletions

File tree

‎.changeset/stale-query-removal.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/query-core': patch
3+
---
4+
5+
Ignore removal requests for query instances that are no longer stored in the cache.

‎packages/query-core/src/__tests__/queryCache.test.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,18 +419,22 @@ describe('queryCache', () => {
419419
})
420420

421421
describe('QueryCache.remove', () => {
422-
it('should only delete the instance currently stored under its queryHash', () => {
422+
it('should be a no-op if the query is no longer the cached instance', () => {
423423
const key = queryKey()
424424

425425
const staleQuery = queryCache.build(queryClient, { queryKey: key })
426426
queryCache.remove(staleQuery)
427427

428428
const currentQuery = queryCache.build(queryClient, { queryKey: key })
429429
expect(currentQuery).not.toBe(staleQuery)
430+
const subscriber = vi.fn()
431+
const unsubscribe = queryCache.subscribe(subscriber)
430432

431433
queryCache.remove(staleQuery)
432434

433435
expect(queryCache.get(hashKey(key))).toBe(currentQuery)
436+
expect(subscriber).not.toHaveBeenCalled()
437+
unsubscribe()
434438
})
435439
})
436440

‎packages/query-core/src/queryCache.ts‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -208,13 +208,9 @@ export class QueryCache extends Subscribable<QueryCacheListener> {
208208
remove(query: Query<any, any, any, any>): void {
209209
const queryInMap = this.#queries.get(query.queryHash)
210210

211-
if (queryInMap) {
211+
if (queryInMap === query) {
212212
query.destroy()
213-
214-
if (queryInMap === query) {
215-
this.#queries.delete(query.queryHash)
216-
}
217-
213+
this.#queries.delete(query.queryHash)
218214
this.notify({ type: 'removed', query })
219215
}
220216
}

0 commit comments

Comments
 (0)