T
TanStack2y ago
fair-rose

Custom query hook and type for placeholderData option

Hi! I'm currently trying to migrate from v3 to v5 and have an issue with defining the type for placeholderData option that I'm using with keepPreviousData helper function. We've got our own basic UseQueryOption type defined with a few of the common options (e.g. enabled, keepPreviousData) that we use with our custom query hooks. Until now, keepPreviousData was simply a boolean, but now placeholderData is a generic type that depends on the response type. What's the best way to type it? Right now, most of our custom query hooks are typed as:
// file with types
type UseQueryOptions = {
enabled?: boolean
keepPreviousData?: boolean
}

// file with hook
const useCustomQuery = (params: UseCustomQueryParams, options?: UseQueryOptions) => {
...
return useQuery({...})
}
// file with types
type UseQueryOptions = {
enabled?: boolean
keepPreviousData?: boolean
}

// file with hook
const useCustomQuery = (params: UseCustomQueryParams, options?: UseQueryOptions) => {
...
return useQuery({...})
}
What's the best way to provide a type for placeholderData in UseQueryOptions?
3 Replies
robust-apricot
robust-apricot2y ago
you can keep the flag and translate it inside useCustomQuery to the function isn't that the advantage of any abstraction - that you don't need to distribute underlying changes to the whole codebase ?
fair-rose
fair-roseOP2y ago
Thanks so much for a quick answer! It looks like the easiest solution. I might need to provide default options now though, as without something like:
useQuery({
...
placeholderData: options?.keepPreviousData ? keepPreviousData : undefined,
}
useQuery({
...
placeholderData: options?.keepPreviousData ? keepPreviousData : undefined,
}
Passing keepPreviousData: true won't have any effect.
robust-apricot
robust-apricot2y ago
Yes, that's the way

Did you find this page helpful?