What steps do I need to take to transform my existing profile page into a seamless infinite scrolling experience?

In my Firestore database, there are numerous profile documents that I want to display on a webpage using v-for. My goal is to show only 4 documents at a time and then load another set of four as the user scrolls for a smoother experience.

I initially attempted to retrieve just four documents, but I struggled with getting the next set of four instead of repeating the same ones. Despite trying various online examples, I couldn't find a solution that worked.

Below is the JavaScript snippet responsible for fetching profiles from Firestore:

const getPremium = () => {
    const Premium = ref([])
    const error = ref(null)

    const load = async () => {
        try{
            const res = await projectFirestore.collection('Premium').limit(4).get()

            Premium.value = res.docs.map(doc => {
                console.log(doc.data())
                return {...doc.data(), id: doc.id}
            })
        }
        catch (err){
            error.value = err.message
            console.log(error.value)
        }
    }

    return { Premium, error, load}
}

export default getPremium

Here's the Vue code where I aim to showcase all profiles with infinite scrolling:

<script setup>
import getPremium from "../Composables/getPremium.js";
const {Premium, error, load} = getPremium();
load();
</script>

<template>
<br> 
 <div class="grid ...">

 <div v-for ="Premiums in Premium" :key="Premiums.id">
   <router-link :to="{ name: 'Samplepremium', params: { id: Premiums.id }}">
     <div class= "hover:scale-105 ...">
       <br>
         <p class="text-xl">{{ Premiums.name }}</p>
           <div class="relative">
             <img :src= "Premiums.Pic1"  class="object-contain ...">
             <p class="bg-red-700 text-slate-300 ...">{{ Premiums.det1 }}</p>
             <p class="bg-red-700 text-slate-300 ..."> {{ Premiums.det2 }} </p>
           </div>
           <div class="grid grid-cols-2 grid-rows-fit text-left ml-6">
             <p>Age:</p>
             <p>{{ Premiums.det3 }}</p>
             <p>Location:</p>
             <p>{{ Premiums.det4 }}</p>
             <p>Rates:</p>
             <p>{{ Premiums.det5 }} /hr</p>
             <p>Phone:</p>
             <p>{{ Premiums.det6 }}</p>
           </div>
           <br>
     </div>
   </router-link>
 </div>

</template>

I have omitted my unsuccessful attempts to fetch another set of four profiles as it resulted in displaying the same set repeatedly. Any guidance on how to achieve this within the provided code would be highly appreciated.

Answer №1

When fetching new data, it's important to use an offset value. While my experience with firebase is limited, the startAt method seems like a good option. One approach you could take is to store the current offset of your data and then trigger the method with that offset when you reach the point where new data should be loaded.

To learn more about the startAt method, check out this resource: https://firebase.google.com/docs/firestore/query-data/query-cursors

Here's an example of how you could implement this:

const load = async (offset = 0) {
     try{
        const res = await projectFirestore.collection('Premium').limit(4).startAt(offset).get()

        Premium.value = res.docs.map(doc => {
            console.log(doc.data())
            return {...doc.data(), id: doc.id}
        })
    }
    catch (err){
        error.value = err.message
        console.log(error.value)
    }
}

In addition to this function, you'll also need a scroll method to monitor the position of elements in the user's browser window. When you reach the designated point on the page, simply call the function again with the offset parameter included.

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

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

How can I retrieve the component label in Vuetify's validation rule function?

Is there a way to access the properties of a component within its "Rules" function in order to retrieve a localized field name for error messages? <v-text-field v-model="obj.count" :counter="10" :label="this.$l ...

Activate the console.log functionality if it has been previously turned off

When working on a project, I noticed that console.log is disabled. Although Firefox alerts me about this, I don't have the time to locate where in the code it's disabled. Is there a method for overriding the disabling of console.log specifically ...

Choosing between radio buttons either horizontally or vertically within a table

Here is the markup I am working with: <table> <tr> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></td> <td><input type="radio" name="radio"></ ...

What is the best way to integrate the express-session logic with Prisma for optimal performance?

Hi there, I recently started using Prisma and want to integrate it with PostgreSQL. My main goal is to implement authentication in my backend, but I encountered issues while trying to create a session table. When working with raw SQL, I managed to add the ...

Using Jquery to show items in a nested loop

I have a requirement to showcase items owned by different customers. To achieve this, I utilize an ajax call to fetch the data and then group it based on individual customer identities. Subsequently, I append the grouped data to my HTML structure. The for ...

Verifying if the arrangement of children within a div element is in the right sequence

I am presenting an object that resembles the following structure <div class="some class"> <h3>This is H3 tag</h3> <h1>Testing H1 element</h1> <p>Hey this is p tag</p> <h3>This is H3 tag</ ...

An error occurred when attempting to search for 'length' using the 'in' operator in the context of the Datatables plugin and jQuery 1.11.3

I implemented the jQuery Datatables plugin in my tables for pagination, sorting, and searching functionalities. However, I am facing issues where the elements are not working properly, and the pagination occasionally fails to display. The Chrome console is ...

Why does the function yield two distinct outcomes?

I can't figure out why, but when I execute the function (kpis1) by itself, it returns the result (100), however, when I run the function (kpis2) alone, I get the result (97). But when I run both functions together, the results are kpis1=100 and kpis2 ...

Achieving dynamic serving of static files using Rollup and integrating seamlessly with node-resolve

Currently, I am in the process of building a library using TSDX, which is a powerful CLI tool for package development based on Rollup. My project involves a collection of country flags SVGs that need to be imported and displayed dynamically when required. ...

Encountering a CSS issue during the edit process with PHP and JavaScript

I'm encountering an issue when clicking on the edit button, as my data fetched from the DB should be displayed inside a text field. However, I'm facing a CSS-related error: Uncaught TypeError: Cannot read property 'style' of null Belo ...

Passing Data using Props in Vue 3 and Vue Router Leads to Invalid Parameters Alert

Currently, I am working on a project using Vue 3 and attempting to pass data between views via Vue Router. Specifically, I am aiming to transfer data from JobSelection.vue to Invoice.vue by utilizing router parameters. In my index.js file, I have defined ...

What causes AsyncStorage to lose one value while another value remains intact?

My last session id is stored using AsyncStorage, but for some reason it loses a specific value and I can't figure out why. I created an app that should automatically select the last chosen group on startup. However, after restarting the app, AsyncSto ...

The browser has the ability to execute scripts prior to processing any post requests

When it comes to handling post requests, browsers have the ability to process scripts. Imagine you have the following scenario: if (some true condition) { console.log("ready to post") restangular.all.post(RequestData).then(function(response){ ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Combine items based on their keys and corresponding values

The original question has been updated for clarity. The desired output is to merge an array of objects into a single object with specific conditions. I am attempting to consolidate three sets of keys per object into one instance, choosing the lowest numbe ...

Issue of displaying buttons based on sibling's height under certain conditions

OBJECTIVE I have undertaken a project to enhance my skills in React and TypeScript by developing a UI chat interface. The design requirement is that when a chat message has enough vertical space, its action buttons should appear stacked vertically to the ...

Problems with Navbar rendering on multiple occasions

GENERAL INFO I've encountered an issue with the re-rendering of my sidemenu in Gatsby. Despite my efforts, I can't prevent the sidemenu from re-rendering and overriding the data that I set for it. const [activeParent, setActiveParent] = useState ...

Retrieval of entity through REST Endpoint using ODataSetName for Custom Entity

In my restendpoint.js file, I have a function called retrieveRecord which is defined on this website I am working on a function that should trigger whenever the Programme (a lookup field) on the Application entity changes. The goal is to fetch the attribu ...

Create a stylesheet document.write function that will never be true

While examining the source code of a webpage, I stumbled upon this intriguing piece of JavaScript right after the standard stylesheet declaration: <script type="text/javascript"> if('' != '') { document.write("< ...