TanStackT
TanStack11mo ago
9 replies
wispy-yellow

Can I normalize every queryKey globally?

I have an issue where queryKey is used inconsistently across the project—it can be an object, an array, etc. To standardize it, I created a function normalizeQueryKey that sorts each key and converts it into a string.

For example:
const keys = ["user", 123, true, null, undefined, { id: 1, name: "Test" }, { name: "Test", id: 1 }, NaN, Infinity, -Infinity, new Map()];
normalizeQueryKey(keys);
// Returns: ['user', '123', 'true', 'null', 'undefined', '{"id":"1","name":"Test"}', '{"id":"1","name":"Test"}', 'NaN', 'Infinity', '-Infinity', 'NaN', '{}']

const cyclicObj: any = { a: 1 };
cyclicObj.b = cyclicObj;
normalizeQueryKey(["user", cyclicObj]);
// Returns: ['user', '{"a":"1","b":"[Circular]"}']

Now, I manually normalize every queryKey.

❓ My question is: Can I normalize every queryKey globally?
I tried using queryKeyHashFn, but I noticed that queryKey remains unchanged—it only formats queryHash. As a result, if queryKey is different, TanStack Query still triggers a refetch.

So, is there a way to normalize every queryKey globally?
Was this page helpful?