Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/spicy-dates-match.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@tanstack/query-core': patch
---

fix(`partialMatchKey`): distinguish query keys that differ only by a `Date`

Non-exact key matching (used by `invalidateQueries`, `refetchQueries`, `removeQueries`, `cancelQueries`, etc.) traversed objects structurally, so two keys differing only by a `Date` value (e.g. `['report', { from: dateA }]` vs `['report', { from: dateB }]`) were treated as equal even though `hashKey` stores them as separate queries. `partialMatchKey` now compares non-plain objects the same way `hashKey` serializes them, keeping non-exact matching consistent with cache identity.
22 changes: 22 additions & 0 deletions packages/query-core/src/__tests__/utils.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,28 @@ describe('core/utils', () => {
const b = [{ a: null, c: 'c', d: [{ d: 'd ' }] }]
expect(partialMatchKey(a, b)).toEqual(false)
})

it('should distinguish different `Date` values, consistent with `hashKey`', () => {
expect(partialMatchKey([new Date(0)], [new Date(1000)])).toEqual(false)
expect(
partialMatchKey(
['report', { from: new Date(0) }],
['report', { from: new Date(1000) }],
),
).toEqual(false)
})

it('should return `true` for equal `Date` values', () => {
expect(partialMatchKey([new Date(0)], [new Date(0)])).toEqual(true)
})

it('should match non-plain objects that hash equally (e.g. `Map`)', () => {
// `Map`/`Set` serialize to `{}` via `hashKey`, so they share a cache
// entry and must keep matching, unlike `Date`.
expect(
partialMatchKey([new Map([['a', 1]])], [new Map([['a', 2]])]),
).toEqual(true)
})
})

describe('replaceEqualDeep', () => {
Expand Down
14 changes: 13 additions & 1 deletion packages/query-core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,19 @@ export function partialMatchKey(a: any, b: any): boolean {
}

if (a && b && typeof a === 'object' && typeof b === 'object') {
return Object.keys(b).every((key) => partialMatchKey(a[key], b[key]))
// Plain objects and arrays are matched structurally. Other objects
// (e.g. `Date`) are compared the same way `hashKey` serializes them, so
// that non-exact matching stays consistent with how queries are stored.
if (
(isPlainArray(a) && isPlainArray(b)) ||
(isPlainObject(a) && isPlainObject(b))
) {
return Object.keys(b).every((key) =>
partialMatchKey((a as any)[key], (b as any)[key]),
)
}

return hashKey([a]) === hashKey([b])
}

return false
Expand Down