Trouble with Type Inference for useInfiniteQuery in TanStack Query v5 #7075
-
Hello everyone, I've encountered an issue with type inference when using useInfiniteQuery from TanStack Query v5 in a TypeScript project. Despite explicitly typing the return of my custom hook, the TypeScript compiler does not infer the expected UseInfiniteQueryResult type. Here's a simplified version of my hook: export const useReviewBoardReadListInfiniteQuery = (
params?: ReviewBoardParams,
config?: UseInfiniteQueryOptions<ServerPaginationData<ReviewBoardResponse[]>>
): UseInfiniteQueryResult<ServerPaginationData<ReviewBoardResponse[]>> => {
const fetchFn = async ({
pageParam = 0,
}): Promise<ServerPaginationData<ReviewBoardResponse[]>> => {
// Fetch logic...
};
return useInfiniteQuery({
queryKey: ['reviewBoardReadListInfinite', params],
queryFn: ({ pageParam }) => fetchFn({ pageParam }),
initialPageParam: 0,
// Additional configuration...
...config,
});
}; When using this hook in a component, I intended for the data property to be inferred as ServerPaginationData<ReviewBoardResponse[]> | undefined, but instead, TypeScript infers it as UseInfiniteQueryResult<ServerPaginationData<ReviewBoardResponse[]>, Error>, which seems to miss aligning with the explicit return type I provided. Here's how I use the hook: const { data, fetchNextPage, hasNextPage, isError, isFetchingNextPage } = useReviewBoardReadListInfiniteQuery({
limit: 15,
isPublished: true,
}); And the error I'm seeing is related to accessing data.pages, where TypeScript doesn't recognize pages as part of data. I've checked my types and configurations against the documentation but can't seem to pinpoint the issue. Has anyone faced a similar problem or can offer insight into what I might be doing wrong? Any suggestions on how to ensure the correct type inference for useInfiniteQuery would be greatly appreciated.
Thank you in advance for your help! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
The following code does work, but it seems like I might be using it incorrectly. I would appreciate any help: ...
const { data, fetchNextPage, hasNextPage, isError, isFetchingNextPage } = useReviewBoardReadListInfiniteQuery({
limit: 15,
isPublished: true,
})
const reviews = (data as unknown as InfiniteData<ServerPaginationData<ReviewBoardResponse[]>>)?.pages
.map((page) => page?.items)
.flat()
... |
Beta Was this translation helpful? Give feedback.
-
show a typescript playground please |
Beta Was this translation helpful? Give feedback.
everything is easier if you don't spread
...config
. You'd need to set all type parameters onUseInfiniteQueryOptions
playground