Skip to content

Commit 1dd372f

Browse files
fix(query-core): replaceEqualDeep correctly handles values that contain undefined (TanStack#6719)
1 parent c08abf0 commit 1dd372f

File tree

2 files changed

+32
-3
lines changed

2 files changed

+32
-3
lines changed

packages/query-core/src/tests/utils.test.tsx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,24 @@ describe('core/utils', () => {
332332
const result = replaceEqualDeep(obj1, obj2)
333333
expect(result).toStrictEqual(obj2)
334334
})
335+
336+
it('should be able to share values that contain undefined', () => {
337+
const current = [
338+
{
339+
data: undefined,
340+
foo: true,
341+
},
342+
]
343+
344+
const next = replaceEqualDeep(current, [
345+
{
346+
data: undefined,
347+
foo: true,
348+
},
349+
])
350+
351+
expect(current).toBe(next)
352+
})
335353
})
336354

337355
describe('matchMutation', () => {

packages/query-core/src/utils.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,8 @@ export function replaceEqualDeep(a: any, b: any): any {
224224
const array = isPlainArray(a) && isPlainArray(b)
225225

226226
if (array || (isPlainObject(a) && isPlainObject(b))) {
227-
const aSize = array ? a.length : Object.keys(a).length
227+
const aItems = array ? a : Object.keys(a)
228+
const aSize = aItems.length
228229
const bItems = array ? b : Object.keys(b)
229230
const bSize = bItems.length
230231
const copy: any = array ? [] : {}
@@ -233,9 +234,19 @@ export function replaceEqualDeep(a: any, b: any): any {
233234

234235
for (let i = 0; i < bSize; i++) {
235236
const key = array ? i : bItems[i]
236-
copy[key] = replaceEqualDeep(a[key], b[key])
237-
if (copy[key] === a[key] && a[key] !== undefined) {
237+
if (
238+
!array &&
239+
a[key] === undefined &&
240+
b[key] === undefined &&
241+
aItems.includes(key)
242+
) {
243+
copy[key] = undefined
238244
equalItems++
245+
} else {
246+
copy[key] = replaceEqualDeep(a[key], b[key])
247+
if (copy[key] === a[key] && a[key] !== undefined) {
248+
equalItems++
249+
}
239250
}
240251
}
241252

0 commit comments

Comments
 (0)