Tips for creating an endless scrolling/loader feature in Nuxt?

Hey there! I am looking to display data after implementing infinite loading. The data is sent asynchronously using asyncData to the page with an ID.

Page

<script>
export default {
  async asyncData({ $axios, store }) {
    const customerId = store.getters['user/auth/customerId']
    if (!customerId) {
      return
    }
    const products = await customerApi.getProducts(
      { $axios },
      customerId,
      this.page
    )
    return {
      products,
    }
  },
  data() {
    return {
      page: 1,
    }
  },
}
</script>

I have the initial data for the first page. The 'products' are passed as props to my template. In the template, I have implemented infinite loading functionality.

template

<template>
  <generic-button v-if="!viewMore" inline @click="viewMore = true">
    see more
  </generic-button>
  <client-only v-else>
    <infinite-loading
      :distance="800"
      force-use-infinite-wrapper
      @infinite="infiniteHandler"
    ></infinite-loading>
  </client-only>
</template>

<script>
export default {
  components: {
    InfiniteLoading: () =>
      process.client
        ? import('vue-infinite-loading')
        : Promise.resolve({ render: (h) => h('div') }),
  },
  props: {
    products: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      page: 1,
    }
  },
  methods: {
    infiniteHandler($state) {
      // This method will retrieve new data when pagination changes
    },
  },
}
</script>

I want to trigger a new asyncData request with an incremented page parameter and display the updated data every time the pagination is initiated.

Thank you!

Answer №1

Although not my preferred choice, I was able to successfully implement the vue-infinite-loading package.

Check out the final result with the required Parent/Child relationship.

parent page

<template>
  <div>
    <nuxt-link :to="{ name: 'redirect' }">
      Go to another page and come back to have this one triggered
    </nuxt-link>

    <child ref="child" :users="users" @fetchMore="callApi"></child>
  </div>
</template>

<script>
export default {
  name: 'ParentPage',
  async asyncData({ $axios }) {
    const { data } = await $axios.$get(
      'https://reqres.in/api/users?per_page=2&page=1'
    )
    return { users: data }
  },
  methods: {
    async callApi(newPageAsked) {
      const { data: newUsers } = await this.$axios.$get(
        `https://reqres.in/api/users?per_page=2&page=${newPageAsked}`
      )
      console.log('new users fetched? ', newUsers)

      if (newUsers.length) {
        this.users = [...this.users, ...newUsers]
        this.$refs.child.$refs.infiniteLoader.stateChanger.loaded()
      } else {
        this.$refs.child.$refs.infiniteLoader.stateChanger.complete()
      }
    },
  },
}
</script>

Child.vue

<template>
  <div class="small-height">
    <div v-for="user in users" :key="user.id">
      <p class="user">
        <span>{{ user.first_fame }}</span>
        <span>{{ user.last_name }}</span>
        <br />
        <span>{{ user.email }}</span>
        <br />
        <img :src="user.avatar" />
      </p>
    </div>

    <infinite-loading
      ref="infiniteLoader"
      @infinite="infiniteHandler"
    ></infinite-loading>
  </div>
</template>

<script>
import InfiniteLoading from 'vue-infinite-loading'

export default {
  name: 'Child',
  components: {
    InfiniteLoading,
  },
  props: {
    users: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      page: 1,
    }
  },
  methods: {
    infiniteHandler($state) {
      this.page += 1
      this.$emit('fetchMore', this.page)
    },
  },
}
</script>

<style scoped>
.small-height {
  height: 200px;
  border: 2px solid red;
  width: 400px;
  overflow-y: auto;
}
.user {
  height: 200px;
}
</style>

Take a look at the GitHub repository for this project, or see the live version here!

I've included comments and details in the Network tab for insight into what's happening. Utilized reqres.in for simulating a paginated API.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Protractor encounters an "Error starting WebDriver session" message

After starting a server with webdriver-manager start, encountering an error when attempting to run protractor: Using the selenium server at http://127.0.0.1:4444/wd/hub [launcher] Running 1 instance of WebDriver ERROR - Unable to initiate a WebDriver sess ...

Is there a way to switch the classList between various buttons using a single JavaScript function?

I'm currently developing a straightforward add to cart container that also has the ability to toggle between different product sizes. However, I am facing difficulties in achieving this functionality without having to create separate functions for ea ...

generating a dynamic tree structure with JSON by leveraging a database

It was brought to my attention that I am facing a unique challenge: I am trying to generate a JSON tree using Java/JavaScript with data sourced from a MySQL Database. I have not been able to locate the appropriate documentation for this task Any assistan ...

Using regular expressions in Javascript to extract decimal numbers from a string for mathematical operations

I'm currently working on a Vue method where I extract information from a WordPress database. The data retrieved sometimes contains unnecessary text that I want to filter out. Using the prodInfo variable, the input data looks something like this: 2,5k ...

Verify record removal without a PHP click

My website features a navigation menu that streamlines the browsing experience: <form action="../"> <select onchange="window.open(this.options[this.selectedIndex].value,'_top')"> <option value="" selected="selected">Navigate< ...

How to properly handle file uploads and get the correct image path from Node Js (Express) to React Js?

Currently, I am working on my local system developing a file upload feature using node js. My project file structure looks like this: Project ..client .... source code of React App ..Server ....uploads ......avatar ........image.png ....index.js In this ...

Browser encountering HTTP response that has been shorted extensively

When making an HTTP post request using axios, I am encountering an issue where the body of the response is a large 4MB string. axios({ method: 'POST', url: url, data: data, headers : headers, }) .then(function (response) { co ...

Sending a post request using an AngularJS service

I have implemented the following code in my application. The dataService holds all the $http requests in my app. In the controller, I am using this function to call a Web Api service which returns the correct response. However, when the function customer ...

Guide on updating a MongoDB document upon clicking a button on an HTML page

I'm new to backend development and I've been working on creating a CRUD notes application without using React or EJS. My current issue is that I am unable to edit documents. The desired functionality is for the user to be directed to a page wher ...

Every time I alter the pathway, the music suddenly ceases. How can I create a constantly changing audio experience?

I'm facing an issue with a dynamic audio player on my website. On a page featuring music, when I click 'play' on any song, it triggers a function: playSong (song) { var payload = { name: song, audio: new Audio(require(` ...

I am currently utilizing react-admin, however, I am encountering an issue with the heavy build causing errors

Currently, I am working on developing the frontend using react-admin. Initially, I intended to utilize NextJS and found a helpful reference article. Reference: When attempting to run next dev, everything worked smoothly without any errors. However, when ...

Issues with Laravel 6 user authentication functionality

Today I set up a new project with Laravel version 6.x. Having PHP 7.3 on my system, the installation of laravel 6 went smoothly. Next, I executed the following command to enable Auth UI for VueJS: artisan ui vue —auth and also ran this command: comp ...

Navigating through an array and Directing the Path

My array contains objects as shown below: const studentDetails = [ {id:1, name:"Mike", stream:"Science", status:"active"}, {id:2, name:"Kelly", stream:"Commerce", status:"inactive"}, { ...

Creating a Yeoman application with a personalized Node.js server

As I embark on the journey of developing a node.js and angular application using the powerful Yeoman tool, I can't help but wonder about one thing. Upon generating my application, I noticed that there are predefined tasks for grunt, such as a server ...

What is the method for displaying x-axis dates below a highchart?

I'm encountering an issue with Highcharts where dates are not showing under the chart when passing series data as an array of objects. See result image The documentation mentions using an object instead of an array ([1649153340000, 45]docs I need t ...

Customizing the language parameter for the apply button script on LinkedIn

Our company's website features the AWLI button which allows users to apply for jobs using their LinkedIn profile. <div name="widget-holder"> <script type="text/javascript" src="https://www.linkedin.com/mj ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

Storing dynamic values in the Vuex state management system

Running a basic store, I'm looking to create a value that automatically adds up all values in an array. However, I'm uncertain whether mutations, methods, or computed values would be the best approach. export default { namespaced: true, s ...

What causes Bootstrap to malfunction when the route contains double slashes?

When using /something, everything works fine, but when switching to /something/somethingelse, Bootstrap fails to function. It seems that the number of "/" characters in the route is causing this issue, rather than the content inside the .ejs file. Here is ...

Is the Utilization of Inline JavaScript in HTML Attributes by Angular considered a "good practice"?

While going through the Angular tutorials, I found a lot to like. However, I couldn't help but wonder if "ng-click" is not essentially just an inline onClick function. My understanding was that the JavaScript community frowned upon using inline JavaSc ...