Last active
February 28, 2021 13:12
-
-
Save joeynimu/948ba9626115e0adcf3bf3e23c49cf3e to your computer and use it in GitHub Desktop.
Updating
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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