Making paginated HTTP request in JS using the fetch
method,
BASE_URL = 'https://jsonmock.hackerrank.com/api/football_matches'
async function fetchMatches() {
let page_number = 1;
const all_matches = [];
try {
while(true) {
console.log(`Fetching page ${page_number}`);
const URL = `${BASE_URL}?year=2011&page=${page_number}`;
const data = await fetch(URL);
if(!data.ok) {
console.log(data.status);
}
const matches = await data.json();
all_matches.push(matches?.data);
if (page_number == matches?.total_pages) {
console.log('Fetched all pages');
break;
}
page_number += 1;
}
return all_matches;
} catch(err) {
console.log(`Error fetching matches: ${err}`);
return [];
}
}
fetchMatches().then((matches) => {
console.log(matches);
});