Infinite scroll | Pagination on an API using JavaScript Generators
Write clean codes using JavaScript GeneratorsTo
While writing Frontend code, You may have a scenario where you have to fetch all records from an API using pagination. You can break the code into multiple functions to do so. However, maintaining so many variables and passing states from one function to another function, is not simple as it looks. The async nature of the data source makes it more complex. However, you can use the async-generator functions to simplify it. In this article, I will explain how you can break this complex logic into simplified functions.
1. Create a mocked data lake/source
To test out the functionality you required a data source. To mimic the real-api data source, I will create a list of dummy users.
const users = Array(1000)
.fill()
.map((_, i) => ({ name: `user${i}`, id: `id_${i}` }));
const TOTAL_RECORDS = users.length;
console.log({user: users[0], TOTAL_RECORDS});
// { user: { name: 'user0', id: 'id_0' }, TOTAL_RECORDS: 1000 }
2. Fetch users API function
You can use a promise-based API function to fetch records. However, I will use async-await function to create this Fetch user API function
//service.js
const delay = () => new Promise((r) => setTimeout(r, 1000));
/**
* fetchUsers
*
* @param {page, limit} current page number, limit of the records to fecth
* @default {0, 100}
* @returns
*/
const fetchUsers = async ({ page = 0, limit = 100 }) => {
const start = page * limit; // start index of the records
const end = (page + 1) * limit; // end index of the records
await delay(); // virtual delay of 1000ms
return {
data: users.slice(start, end), //Slice the records from start to end
done: end >= TOTAL_RECORDS,
start,
end,
};
};
// [optional]
//export { fetchUsers };
The above function fetchUsers
takes options like page
and limit
. Page is defined as the current page of the pagination and limit is defined as the limit of records to be fetched. Delay is just and virtual delay of 1000ms to mimic the actual network.