Nuxtstop

For all things nuxt.js

How To Implement an Infinite Scroll with Vue and Nuxt

5 0

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 -
API response

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)
       }


    },
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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()
            }
        }
Enter fullscreen mode Exit fullscreen mode

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.
null in next response

Situation can be different in different API response.