Last active
January 16, 2023 19:02
-
-
Save perjo927/84f071a569a367ee0cd93f0a64b5de68 to your computer and use it in GitHub Desktop.
Generator function for paginating async data
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
// Mock data | |
const fakePaginatedData = [ | |
{ | |
next: 'https://fake-api.com/cars?page=2', | |
results: [ | |
{ model: 'Volvo XC40', year: '2020', price: '30000' }, | |
{ model: 'Renault Clio', year: '2019', price: '10000' }, | |
{ model: 'Toyota Aygo', year: '2022', price: '20000' }, | |
], | |
}, | |
{ | |
next: null, | |
results: [ | |
{ model: 'Mercedes-Benz GLC 200', year: '2020', price: '50000' }, | |
{ model: 'Nissan Qashqai', year: '2022', price: '40000' }, | |
], | |
}, | |
]; | |
// Fake implementation of fetch() | |
async function fakeFetch(url) { | |
const params = new URLSearchParams(new URL(url).search); | |
const page = params.get('page'); | |
const { results, next } = fakePaginatedData[page ? page - 1 : 0]; | |
return { | |
json: async () => ({ | |
results, | |
next, | |
}), | |
}; | |
} | |
// Generator function for paginating async data | |
async function* getPaginator(url) { | |
let nextUrl = url; | |
while (nextUrl) { | |
const response = await fakeFetch(nextUrl); | |
const { next, results } = await response.json(); | |
nextUrl = next; | |
// you can also use "yield*" for unpacking the sequence | |
yield results; | |
} | |
} | |
// Pseudo-implementation of infinite scroll handler | |
async function onScroll(paginator) { | |
// trigger another iteration of the while loop | |
const page = await paginator.next(); | |
if (page?.done) { | |
return; | |
} | |
console.log(page.value); | |
} | |
async function main() { | |
const paginator = getPaginator('https://fake-api.com/cars'); | |
onScroll(paginator); // [{…}, {…}, {…}] | |
onScroll(paginator); // [{…}, {…}] | |
onScroll(paginator); // nothing (done: true) | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment