T
TanStack9mo ago
conscious-sapphire

How to handle query key requiring object with bigint?

A complex object with bigints should be set as a dependency in the queryKey array, however react-query errors as it is unable to parse the object. How to solve this?
3 Replies
absent-sapphire
absent-sapphire9mo ago
I think you'd have to write your own queryKeyHashFn and use superjson to do the serialization This is what's used by default
/**
* Default query & mutation keys hash function.
* Hashes the value into a stable hash.
*/
export function hashKey(queryKey: QueryKey | MutationKey): string {
return JSON.stringify(queryKey, (_, val) =>
isPlainObject(val)
? Object.keys(val)
.sort()
.reduce((result, key) => {
result[key] = val[key]
return result
}, {} as any)
: val,
)
}
/**
* Default query & mutation keys hash function.
* Hashes the value into a stable hash.
*/
export function hashKey(queryKey: QueryKey | MutationKey): string {
return JSON.stringify(queryKey, (_, val) =>
isPlainObject(val)
? Object.keys(val)
.sort()
.reduce((result, key) => {
result[key] = val[key]
return result
}, {} as any)
: val,
)
}
conscious-sapphire
conscious-sapphireOP9mo ago
I seem to remember reading that react-query sorts the keys deterministically (or something like that), would that be lost i using this approach?
absent-sapphire
absent-sapphire9mo ago
I'd say you'd have to account for that yup Something like this should work?
function hashKey(queryKey: QueryKey | MutationKey): string {
return JSON.stringify(queryKey, (_, val) =>
isPlainObject(val)
? Object.keys(val)
.sort()
.reduce((result, key) => {
result[key] = superjson.stringify(val[key]);
return result
}, {} as any)
: superjson.stringify(val),
)
}
function hashKey(queryKey: QueryKey | MutationKey): string {
return JSON.stringify(queryKey, (_, val) =>
isPlainObject(val)
? Object.keys(val)
.sort()
.reduce((result, key) => {
result[key] = superjson.stringify(val[key]);
return result
}, {} as any)
: superjson.stringify(val),
)
}

Did you find this page helpful?