How can Vue use Firebase queries to implement infinite loading for displaying successive results?

I am currently working on developing a food ordering system. My focus is on creating the order history page and implementing infinite loading functionality.

My goal is to display the next five results each time the user clicks the "next" button, in descending order based on the created_at column.

However, I'm encountering an issue where clicking the "next" button repeatedly only shows the same set of results (sixth to tenth) every time.

I believe utilizing a for loop in my method could help resolve this issue, as I am using Firebase queries in my implementation.

Here is a snippet of my code:

<template>
    <div>
        // Code continues here...
    </div>
</template>

<script>
import CartSmartphone from "@/mobile/CartSmartphone.vue";
import NavbarMobile from "@/components/NavbarMobile.vue";
import FooterMobile from "@/sections/FooterMobile.vue";
import fireApp from '@/plugins/firebase'
const firebase = require("firebase");
require("firebase/firestore");
const db = firebase.firestore();

export default {
    name: 'UserSmartphone',
    // Components and data methods defined here...
    // Mounted and next page function implementation...
}
</script>

In my code, I am fetching data from the OrdersUser collection and storing it in the history array. I then render this data in the template section using a loop.

Answer №1

Ensure to keep track of the last visible document within your nextPage function to avoid starting the query after the initial 5 documents every time. Here's what you need to do:

  1. Initialize a variable to store the last visible document while populating your list for the first time, as shown below:

    const dbOrdersRef = db.collection('OrdersUser').doc(this.$route.params.id)
                          .collection('Orders').orderBy("created_at", "desc").limit(5);
    dbOrdersRef.onSnapshot((querySnapshot) => {
        querySnapshot.forEach((doc) => {
            const historyData = doc.data()
            this.history.push(historyData)
            this.sample = doc.data().sample
        })
        this.lastVisible = querySnapshot.docs[querySnapshot.docs.length-1];
    })
    
  2. Utilize the lastVisible variable set during the initial load to begin your subsequent query, as illustrated below:

    nextPage() {
         fireApp.auth().onAuthStateChanged((user) => {
             if (user) {
                 const userId = fireApp.auth().currentUser.uid;
                 const next = db.collection('OrdersUser')
                                .doc(userId)
                                .collection('Orders')
                                .orderBy("created_at", "desc")
                                .startAfter(this.lastVisible)
                                .limit(5);
    
                 return next.onSnapshot((nextQuery) => {
                     nextQuery.forEach((doc) => {
                         const nextData = doc.data()
                         console.log(nextData)
                         this.history.push(nextData)
                     })
                     this.lastVisible = nextQuery.docs[nextQuery.docs.length-1];
                 })
    
             };
    
         }) 
    }
    
  1. Add the lastVisible variable to your data() method so it can be accessed in both nextPage() and mounted() using this., as demonstrated below:

    data() {
         return {
             customer: this.$route.params.id,
             history: [],
             sample: "",
             lastVisible: ""
         }
     },
    

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

Issue with passing reactive property to component in Vue 3 application

I am currently working on a Vue 3 application and I am in the process of setting up a store for state management. Within this application, I have several important files that play different roles: app.vue component.vue main.js store.js These files contai ...

Is it possible to use jQuery to create a slide-up effect from the

Could I reverse the animation direction of my dropdown menu? Currently, it expands from the top to bottom. Is there a way to make it expand from the bottom to the top? Code snippet: animate({height:'show',opacity:'show'}, ddsmoothmenu ...

Automating the testing of Google Analytics for every event triggered with Selenium WebDriver

Currently, I am in the process of automating Google Analytics testing using Selenium WebDriver Java bindings on our website. The site is equipped with Google Analytics tracking events attached to key elements, and my goal is to confirm that clicking a spec ...

Iterate over rows in a b-table component in Vue

In the context of Vue bootstrap, a b-table consists of a list with an unknown number of rows. The requirement is to display a remove button only if the email in the row matches that of the currently logged-in user. This functionality currently works for a ...

The issue with the `.load` function in jQuery not functioning properly

I'm currently tackling an issue with a project where I am encountering difficulties with the .load function not working in Google Chrome. Below is the JavaScript code: function link1() { $('#loadarea').html('loading.....' ...

What is the best way to import API Endpoints from various directories in an Express Server?

I have been using a script to load my API endpoints like this: readdirSync('./routes/api').map((r) => app.use( `/api/v1/${r.split('.')[0]}`, require(`./routes/api/${r.split('.')[0]}`) ) ); This script reads eve ...

JavaScript: Scroll Through Images Horizontally with Descriptions for Each Image

I am looking to create a horizontal scroller/slider that will display images with captions underneath each image. The data is provided in an array of objects, so I need to iterate through the data and populate each item in the scroller with the necessary i ...

How come I keep running into the "is not a function" issue when trying to use the generateRequest function with Polymer's iron-ajax

Oops, it seems like there was an error: Uncaught TypeError: this.$.ajax.generateRequest is not a function. The issue seems to be in assets-ajax.html at line 23. <dom-module id="assets-pull"> <style> </style> <template> <but ...

Tips on modifying the structure of a JSON array using a loop

Hello, I am currently extracting data from an API, but I need to transform the data into a different format in order to pass it to a function successfully. The reason for this is that I have a chart that only accepts data in a specific format for it to dis ...

vue-spa breadcrumbs component

I am currently working on enhancing the navigation of my vue-spa project by implementing breadcrumbs. These breadcrumbs should be capable of displaying properties as breadcrumb-items, and each part of a route must be correctly identified as a breadcrumb-it ...

Tips for executing jsfiddle code within Joomla 3.2

I'm having trouble executing this code on my Joomla website. I have Joomla 3.2 installed with the JCK Editor, but the HTML tags are not functioning correctly. Can someone please assist me in running the following code: $("#text10").keyup(functio ...

Is there a method to incorporate lists of varying types in a single v-for loop without causing any issues with type validations?

My current component is designed to display two different datasets, each with their own unique nature of data: state.articleTypeList: string[] state.renderPriceClassNameList: {[key: string]: string[]} To render both datasets within a single v-for componen ...

Can an Updatepanel control be added to a webpage using Javascript or JQuery?

I'm currently working on a project that involves allowing users to drag icons representing user controls onto a web page. For the desired functionality, these user controls must be contained within an updatepanel (or a similar AJAX-enabled frame) so ...

Boosted - Automated Observable with controlled Update alert

Is there a way to create a ComputedObservable in knockout that is computed from non-observable values and manually trigger the Notification? ...

Is there a way to convert this JSON object into HTML table code?

I've been working on tweaking a code snippet I came across, but I'm struggling to get it to function the way I desire. Here is the current Javascript code: function JsonUtil() { /** * Given an object, * return its type as a string. ...

Utilizing dynamic JavaScript values in URL parameters before sending

When it comes to online payments, I need to send parameters to a specific URL. The calculations on my website are done in JavaScript, but the online payment company requires PHP parameters like MD5 hashing. To address this, I attempted to create a hidden ...

Sending confidential data from the view to the controller without relying on form submission

I am looking for a way to pass a hidden field from a view to a controller. Inside index.chtml <div id="root"> ................ @Html.Hidden("HProjectTypeId", "somevalue") </div> The above code snippet is not enclosed within any form tags ...

Kendo UI Scheduler: The system encountered an overflow while converting to a date and time format

Working on a project using .NET MVC and the Kendo UI Scheduler, an open-source tool. The goal is to save, read, update, and delete events from the scheduler into the database using JavaScript. Encountering some challenges in the process - when attempting ...

Exclude a variety of keys using wildcards or regex when conducting comparisons

How can I exclude certain properties in a JSON object that contain specific characters? var obj1 = {name: "James", age: 17, creation: "13-02-2016", deletion: "13-04-2016", foo_x:"", foo_y:"", foo_z:""} var obj2 = {name: "Maria", age: 17, creation: "13-02- ...

Mastering the art of knowing when to implement asynchronous and synchronous programming techniques is essential for

As I explore asynchronous programming in JavaScript, I am faced with the challenge of integrating two email providers: Sendgrid and Mailgun. My goal is to send an email using one provider, and if any errors occur during the process, automatically resend th ...