T
TanStack•3y ago
eastern-cyan

Invalidating queries for queryKeys generated using tkdodo's key factory pattern with optional params

Hey guys, i've followed the excellent patterns defined by @TkDodo 🔮 : https://tkdodo.eu/blog/leveraging-the-query-function-context The only differing thing I have done is that some arguments passed into the query key factory are optional. An example:
export const projectKeys = {
all: [{ entity: "projects" }] as const,
dataUnits: ({
id,
pagination,
order,
desc,
search,
}:
{
id: string;
pagination?: PaginationType;
search?: string;
order?: ProjectDataSortField | undefined;
desc?: boolean | undefined;
}) =>
[
{
...projectKeys.all[0],
scope: "dataUnits",
id,
pagination,
order,
desc,
search,
},
] as const,
export const projectKeys = {
all: [{ entity: "projects" }] as const,
dataUnits: ({
id,
pagination,
order,
desc,
search,
}:
{
id: string;
pagination?: PaginationType;
search?: string;
order?: ProjectDataSortField | undefined;
desc?: boolean | undefined;
}) =>
[
{
...projectKeys.all[0],
scope: "dataUnits",
id,
pagination,
order,
desc,
search,
},
] as const,
This results in valid query keys, and works great, any values not passed in (undefined) are omitted from the query key generated. I can see logged in the react query dev tools for the queryKeys associated with each fetched query. The issue i'm encountering is using this same function to generate the querykey factory for queryKey invalidation. If I log that array returned by this when some of the optional params are omitted, i'll get a load of undefined properties in the query key generated, this means the queryKey invalidation misses. What's the best / most scalable way to approach this. Without doing some clunky filtering out undefined values from the returned query key each time I call it. Many thanks in advance and thank you for the excellent resources @TkDodo 🔮 !
Leveraging the Query Function Context
Use what React Query provides for optimal type safety
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?