diff --git a/packages/query-core/src/__tests__/query.test.tsx b/packages/query-core/src/__tests__/query.test.tsx index 0b3d4889d62..3efbc56aff5 100644 --- a/packages/query-core/src/__tests__/query.test.tsx +++ b/packages/query-core/src/__tests__/query.test.tsx @@ -975,36 +975,46 @@ describe('query', () => { const queryFn = vi.fn() + const data: Array<{ + id: number + name: string + link: null | { id: number; name: string; link: unknown } + }> = Array.from({ length: 5 }) + .fill(null) + .map((_, index) => ({ + id: index, + name: `name-${index}`, + link: null, + })) + + if (data[0] && data[1]) { + data[0].link = data[1] + data[1].link = data[0] + } + queryFn.mockImplementation(async () => { await sleep(10) - - const data: Array<{ - id: number - name: string - link: null | { id: number; name: string; link: unknown } - }> = Array.from({ length: 5 }) - .fill(null) - .map((_, index) => ({ - id: index, - name: `name-${index}`, - link: null, - })) - - if (data[0] && data[1]) { - data[0].link = data[1] - data[1].link = data[0] - } - return data }) - await queryClient.prefetchQuery({ queryKey: key, queryFn }) + await queryClient.prefetchQuery({ + queryKey: key, + queryFn, + initialData: structuredClone(data), + }) + + const query = queryCache.find({ queryKey: key })! expect(queryFn).toHaveBeenCalledTimes(1) + expect(query.state.status).toBe('error') + expect( + query.state.error?.message.includes('Maximum call stack size exceeded'), + ).toBeTruthy() + expect(consoleMock).toHaveBeenCalledWith( expect.stringContaining( - 'StructuralSharing requires data to be JSON serializable', + 'Structural sharing requires data to be JSON serializable', ), ) diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index a8f91a633da..d5137806400 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -356,15 +356,13 @@ export function replaceData< } else if (options.structuralSharing !== false) { if (process.env.NODE_ENV !== 'production') { try { - JSON.stringify(prevData) - JSON.stringify(data) + return replaceEqualDeep(prevData, data) } catch (error) { console.error( - `StructuralSharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`, + `Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${options.queryHash}]: ${error}`, ) } } - // Structurally share data between prev and new data if needed return replaceEqualDeep(prevData, data) }