I am making a website with option to switch between pages. But here comes the problem. Function works normally but when I want to call inside a function that fetches API, then pages on each click go doubled. Instead of 1,2,3,4,5, it goes 1,2,4,8,16... and so on. How can I fix that?
let page = 1
async function getData(url) {
const res = await fetch(url + page);
const data = await res.json();
const results = data.results;
showList(results);
pageBtns.forEach((btn) => {
btn.addEventListener('click', () => changePage(url, btn));
});
}
function changePage(url, btn) {
if (btn.classList.contains('next-btn')) {
document.querySelector('.prev-btn').classList.add('prev-btn--active');
page++;
if (page === 5) {
btn.classList.remove('next-btn--active');
}
} else {
document.querySelector('.next-btn').classList.add('next-btn--active');
page--;
if (page === 1) {
btn.classList.remove('prev-btn--active');
}
}
getData(url)
console.log(page);
}
I've tried to call changePage function without invoking getData inside and it works normally.
The issue you're encountering is due to the fact that each time getData is called, it adds new click event listeners to all your pageBtns without removing the previous ones. This results in the event listeners stacking up and causing the callback function to execute multiple times for a single click, hence the page number doubling instead of incrementing by one.
To fix this issue, you need to ensure that each button has only one event listener attached to it at any time.
Solution