The main goal of my code is to trigger the fetchNumbers()
function (which retrieves numbers from an API) when a user scrolls to the bottom of the page, creating an infinite scroll effect. However, I'm encountering an issue with the condition inside the axios promise (then) block because it's causing two console.log
outputs to occur simultaneously. It seems like the condition is being ignored altogether.
The method I am using is as follows:
methods: {
fetchNumbers (type = 'default', offset = 0, limit = 0) {
return axios.get(globalConfig.NUMBERS_URL)
.then((resp) => {
if (type === 'infinite') {
console.log('infinite fired')
} else {
console.log('default fired')
}
})
}
The issue is suspected to be in the mounted function:
mounted () {
window.onscroll = () => {
let bottomOfWindow = document.documentElement.scrollTop + window.innerHeight > document.documentElement.offsetHeight - 1
if (bottomOfWindow) {
this.fetchNumbers('infinite')
}
}
}
Upon reloading or entering the page, I'm seeing both console outputs appearing simultaneously:
default fired
infinite fired
Sometimes the order of the outputs is reversed.
UPDATE.
Methods that call the fetchNumbers()
function:
async created () {
await this.fetchNumbers()
}
showCats (bool) {
this.showCategories = bool
if (!bool) {
this.category = [1]
} else {
this.category = []
}
this.isActive = true
this.fetchNumbers()
}
UPDATE 2.
I have identified the issue and will provide more details in an answer.
UPDATE 3.
The problem indeed lies within the onscroll
function. I have three pages in my application: the main page, numbers page, and contact page. If I navigate from the numbers page (where the onscroll function is mounted) to the main or contact page, the onscroll function remains attached and triggers the API call when I scroll to the bottom, even if it's not the numbers page. Is there a way to limit this function to only the numbers page?