Implementing the pagination
In this guide, we'll explore how to implement pagination in your application using GraphQL queries. Pagination is essential for handling large data sets, providing a user-friendly way to navigate and interact with the information. We'll cover key concepts and techniques, enabling you to create efficient, scalable, and seamless user experiences with TalentLayer Graph
1-Set and adapt your query
The function first construct a pagination string based on the provided numberPerPage
and offset
parameters. If numberPerPage
is not provided, the pagination string will be empty, which means that the query will fetch all users without pagination.
Next, the function constructs a conditional string that will be used in the GraphQL query to filter the users based on the provided searchQuery
. If no searchQuery
is provided, the conditional string will only contain an empty object.
Then we build the query with our two parameters => pagination and condition
Please find the code here
Other type of query for pagination
As you can see in the query just below is that we add to parameter StartDate and EndDate that will allow us to set up a filter by date on our front end
2-Adapt your hook
We add a few state variable and parameter in the useUsers hook
hasMoreData
: This state variable is a boolean that indicates whether there are more users to fetch. It is initially set totrue
, which means that when the component is first rendered, it assumes there is more data to load. As data is fetched, this state variable will be updated based on the length of the fetched data. If the length of the fetched data is less than the specifiednumberPerPage
, it setshasMoreData
tofalse
, indicating that there are no more users to fetch. it allow you to display a button or a message.loading
: This state variable is a boolean that indicates whether data is being fetched. It is initially set tofalse
. it allow you to display a loader during the fetch process.offset
: This state variable is a number that represents the pagination offset for the users list. It is initially set to0
. When theloadMore
function is called, theoffset
is updated by adding the value ofnumberPerPage
to the current offset. The updated offset is then used in thegetUsers
function to fetch the next set of users.numberPerPage
is the element number you want to display per page, this parameter will be set in the component
Please find the code here
3-Set up the pagination in your component
First we need to set up the parameter needed for useUsers call
will the element number display per page
Then we call the hook useUsers and destructure the return object to get users, hasMoreData, loading and loadMore
You map your users oject and display all the data you want in a dedicated component.
Then we add a button who call loadMore, you can check the hook useUsers with the loadMore function that will trigger setOffset.
Please find the code here
Last updated