T
TanStack11mo ago
absent-sapphire

What would be the correct way to type queryKey if input is a skipToken?

export const useGetProjectQueryKey = (variables: GetProjectRequest) => [
"projects",
variables.params.pid,
];

export const useGetProjectQuery = <TData = Project>(
variables: GetProjectRequest | SkipToken,
{
...options
}: Omit<
UseQueryOptions<Project, Error | ZodError, TData>,
"queryKey" | "queryFn"
> = {},
) =>
useQuery<Project, Error | ZodError, TData>({
queryKey: variables === skipToken ? [] : useGetProjectQueryKey(variables),
queryFn: variables === skipToken ? skipToken : ({ signal }) => getProject(variables, signal),
...options,
});
export const useGetProjectQueryKey = (variables: GetProjectRequest) => [
"projects",
variables.params.pid,
];

export const useGetProjectQuery = <TData = Project>(
variables: GetProjectRequest | SkipToken,
{
...options
}: Omit<
UseQueryOptions<Project, Error | ZodError, TData>,
"queryKey" | "queryFn"
> = {},
) =>
useQuery<Project, Error | ZodError, TData>({
queryKey: variables === skipToken ? [] : useGetProjectQueryKey(variables),
queryFn: variables === skipToken ? skipToken : ({ signal }) => getProject(variables, signal),
...options,
});
If queryFn is a skipToken would it ignore the queryKey? If it does would an empty array suffice?
1 Reply
mute-gold
mute-gold11mo ago
Have variables be optional, and do a variables != null ternary Type of query key in this case would be ["projects", GetProjectRequest | undefined] Only introduce skipToken in ther queryFn ternary You can add as const to the return of useGetProjectQueryKey

Did you find this page helpful?