InfiniteQueries: Can getNextPageParam return an object? #5373
-
Hello! The API endpoint that I work with does not return a cursor and I found 5320 helpful. The API requires to pass in an object export default function useData(params = {}) {
return useInfiniteQuery({
queryKey: ['data', params],
queryFn: () => getDataAsync(params),
getNextPageParam: (lastPage) => {
if (params['$top'] < lastPage['@odata.count']) {
const nextPage = {
...params,
$top: params['$top'] + 50,
$skip: params['$skip'] + 50,
};
return nextPage;
} else {
return undefined;
}
},
});
} I use fetchNextPage to get the next set of records. useEffect(() => {
if (inView) {
fetchNextPage();
}
}, [inView, fetchNextPage]); But I am seeing the same params (used in the first iteration) coming in during the next iteration too. I expect $top and $skip to be incremented by 50, but not happening. Am I doing anything wrong in getNextPageParam? Edit: I understand this will be lot easier in v5 but want to know if there are better alternatives in v4. export default function useData(defaultPageParam) {
return useInfiniteQuery({
queryKey: ['data', defaultPageParam],
queryFn: ({ pageParam = defaultPageParam }) => getDataAsync(pageParam),
getNextPageParam: (lastPage, allPages) =>
allPages.length * defaultPageParam.perPage < lastPage['@odata.count'],
});
}
useEffect(() => {
if (inView) {
const pageParam = {
...oDataQuery,
$top: (data.pages.length + 1) * oDataQuery.perPage,
$skip: data.pages.length * oDataQuery.perPage,
};
fetchNextPage({ pageParam });
}
}, [inView, fetchNextPage, oDataQuery]); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
your initial example would work if you'd add So:
The second approach builds on top of an API that we've removed in v5 (passing params to |
Beta Was this translation helpful? Give feedback.
your initial example would work if you'd add
$skip
and$top
to the result of your QueryFunction (getDataAsync
). Right now, you're probably closing over oldparam
values ingetNextPageParam
(that function should be pure and not close over anything).So:
params
you get into the QueryFuntiongetNextPageParam
, that result is available inlastPage
The second approach builds on top of an API that we've removed in v5 (passing params to
fetchNextPage
), so I wouldn't do that. I'd encourage you to try out v5 alpha and see how it goes. We pass everything (all pageParams) togetNextPageParam
so you won't have that …