T
TanStack14mo ago
quickest-silver

Am I supposed to trim or filter undefined / null / empty strings from query keys?

The UI might not always have optional variables passed into the query key, so the result would be ["foo", "bar", ""] or ["foo", "bar", null] Is this okay? My first assumption is that - it is fine and it would be more overhead to filter falsy values out.
6 Replies
national-gold
national-gold14mo ago
Hi there! Though it is technically ok you may want to re-think your setup as the ambiguity could lead to unintended re-calls and other unwanted behavior. There is an in-depth article which shifted my mindset in creating keys which may help: https://tkdodo.eu/blog/effective-react-query-keys. In your example above if the optional filters could be undefined/null, you may want to consider adding them in an object for more specificity (and better serialization methods*) such as { filters: undefined } as shown in the example here: https://tanstack.com/query/latest/docs/framework/react/guides/query-keys#query-keys-are-hashed-deterministically
rare-sapphire
rare-sapphire14mo ago
sorry to "well actually" this but I'd be cautious with an object having undefined values. We treat { filters: undefined } the same as {} during fuzzy matching and that can be a "gotcha"
rare-sapphire
rare-sapphire14mo ago
GitHub
Query keys with object property set to undefined are not considered...
Describe the bug Query keys with object property set to undefined are not considered equal to missing property. Based on the docs, it should be the same: https://react-query.tanstack.com/guides/que...
national-gold
national-gold14mo ago
Ah intersting! Thanks
quickest-silver
quickest-silverOP14mo ago
What about
{ filters: { order: 'asc', sort: undefined } }
{ filters: { order: 'asc', sort: undefined } }
rare-sapphire
rare-sapphire14mo ago
Has the same problem

Did you find this page helpful?