-
I am having trouble using useInfiniteQuery with a paginated graphql API. My query expects a While this works to get the next set of data, react-query seems to be returning only one page instead of returning the previous page + its results. Hence, the results are from the initial page or last page results. Below is a simplified gist,
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Try taking page out of the cache key, as it will be creating a new cache each time it loads.
|
Beta Was this translation helpful? Give feedback.
-
I think it's a closure problem. When you call I don't think you need the local state for this. - const [page, setPage] = useState(1);
const perPage = 10;
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery(
['data', page, perPage],
- () =>
+ ({ pageParam = 1 }) =>
getPaginatedProductItems({
per_page: perPage,
- page // <- note these variables passed specifically this one. It's used to get a specific page dataset
+ page: pageParam
}),
{
getNextPageParam(lastPage) {
return lastPage.paginated_product_items_v2.page_info.has_next;
},
getPreviousPageParam(firstPage) {
return firstPage.paginated_product_items_v2.page_info.has_previous;
}
}
); for this to work, your
alternatively, you can pass that information directly into
but I would prefer the first approach because it centralises the functionality on the hook call. |
Beta Was this translation helpful? Give feedback.
I think it's a closure problem. When you call
fetchNextPage
, react-query calls thequeryFn
, which closures overpage
from the local state from the time it was created, so it doesn't know about the increment (setPage(page +1 ))
that you have just done.I don't think you need the local state for this.
react-query
injects the result fromgetNextPageParam
into thequeryFn
aspageParam
(have a look at the examples). So you will get whatevergetNextPageParam
produces: