Infinite scrolling is a feature on websites and applications where a user scrolls down and reaches the bottom of the current page of content and then the next page of content is loaded and displayed digital ocean.
My API response look like this, built on django rest -
And now I want to increase the page number and send request for next page result and merge data with my initial data object when user go bottom of page.
data() {
return {
productObj:[],
rawObj:[],
page:1,
}
},
mounted() {
this.scroll()
},
async fetch() {
await this.fetchData()
},
methods:{
scroll () {
window.onscroll = () => {
let bottomOfWindow = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop) + window.innerHeight === document.documentElement.offsetHeight
if (bottomOfWindow) {
this.page++
if(this.rawObj.next){
this.fetchData()
}
}
}
},
async fetchData(){
try{
const res = await this.$axios.$get(`productByPagination/?page=${this.page}`)
this.productObj.push(...res.results)
this.rawObj = res
}
catch({response}){
console.log(response)
}
},
}
Explanation
In first position I set page number 1 in data and send make initial request for storing 1st page data. Then scroll method is responsible when user goes bottom of page it will increase page number and send request to load second page data.
let bottomOfWindow = Math.max(window.pageYOffset, document.documentElement.scrollTop, document.body.scrollTop) + window.innerHeight === document.documentElement.offsetHeight
bottomOfWindow
return true if user go bottom of the page. And if we get true then this piece of code will execute-
if (bottomOfWindow) {
this.page++
if(this.rawObj.next){
this.fetchData()
}
}
Note
In productObj:[],
I stored only my desire result and in rawObj:[],
I stored total response object. And in rawObj has next
which help us to understand is their available any data. If available send another request or make stopped from send another request.
Situation can be different in different API response.
Top comments (5)
Haha, I have to say that I've always used a library for that purpose.
Hence thanks for the blog post. ππ»
I have to say that I've always used a library for that purpose
same to you π ..
I have no longer need to use packages for infinite scroll. Thanks
smoooth!!! Thanks for not making me to search for a pakage for an infinite scroll anyomore hahaha!! (maybe)
You are most welcome.
I'm glad you found this useful π
Please keep in touch for more π€