Skip to content

Instantly share code, notes, and snippets.

@joeynimu
Last active February 28, 2021 13:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save joeynimu/948ba9626115e0adcf3bf3e23c49cf3e to your computer and use it in GitHub Desktop.
Updating
/*
I am having trouble using useInfiniteQuery with a paginated graphql API.
The query expects a `page` variable that is used to get a specific page dataset.
I am currently updating the `page` variable on click the `load more button` and calling the fetchNextPage function.
While this works in terms of getting the next set of data, react-query seems to be returning only on page
instead of returning the previous page + the current page's results. Hence, the results are from the initial page or last page results.
How do I get back results from all the pages?
*/
export default () => {
const [page, setPage] = useState(1);
const {
data,
fetchNextPage,
hasNextPage
} = useInfiniteQuery(["data", page], () => getPaginatedProductItems({
per_page: 10,
page // <- note these variables passed specifically this one. It's used to get a specific page dataset
}), {
getNextPageParam(lastPage) {
return lastPage.paginated_product_items_v2.page_info.has_next;
},
getPreviousPageParam(firstPage) {
return firstPage.paginated_product_items_v2.page_info.has_previous;
},
});
return (<div>
{hasNextPage && < button onClick={() => {
setPage(page + 1); // this is updated so that the API can get the next page of data
fetchNextPage()
}
}> Fetch Next page </button>}
</div>)
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment