Bug Report#
Description#
The hashKey function in @tanstack/query-core throws errors when processing objects or arrays with circular references.
Reproduction Steps#
- Create an object with a circular reference:
const obj = { id: 1 }; obj.self = obj;
- Pass it to
hashKey(obj)
- The function throws a "Maximum call stack size exceeded" error
Expected Behavior#
The function should handle circular references gracefully without throwing an error.
Actual Behavior#
The function throws:
RangeError: Maximum call stack size exceeded for objects with circular references
TypeError: Converting circular structure to JSON for arrays with circular references
Code to Reproduce#
import { hashKey } from "@tanstack/query-core";
const circularObject = { id: 1, name: "test" };
circularObject.self = circularObject;
hashKey(circularObject);
const circularArray = [1, 2, 3];
circularArray.push(circularArray);
hashKey(circularArray);
Root Cause#
The hashKey function uses JSON.stringify with a replacer function, but doesn't handle circular references, which causes JSON.stringify to fail.
Possible Solution#
Implement a circular reference detection mechanism in the replacer function to break circular references.
Environment#
- TanStack Query: 5.100.14
- Node.js: 20.5.1
- Browser: N/A
it is documented that Query Keys need to be serializable using
JSON.stringify:https://tanstack.com/query/v5/docs/framework/react/guides/query-keys
You can provide your own
queryKeyHashFnif you want to opt out of the default behaviour.