I'm having trouble figuring out how to properly paginate data from Firebase without running into errors. Can

Here is the code I have written:

<nav v-if="(tasks.length >= 7)" aria-label="Page navigation example">
    <ul class="pagination fw-bold justify-content-center">
        <li class="page-item">
        <a class="page-link" href="#" aria-label="Previous">
            <span aria-hidden="true">&laquo;</span>
        </a>
        </li>
        <li class="page-item active"><a class="page-link" href="#">1</a></li>
        <li class="page-item" @click="nextTableData"><a class="page-link" href="#">2</a></li>
        <li class="page-item" v-if="(tasks.length > 14)"><a class="page-link" href="#">3</a></li>
        <li class="page-item">
        <a class="page-link" href="#" aria-label="Next">
            <span aria-hidden="true">&raquo;</span>
        </a>
        </li>
    </ul>
</nav>
nextTableData(){
    let q
    this.spinnerShow = true
    if (this.lastdoc != null) {
        q = query(this.todosCollectionRef, orderBy("date", "desc"), startAfter(this.lastdoc));
        console.log(q, this.lastdoc);
    } else {
        q = query(this.todosCollectionRef, orderBy("date", "desc"), limit(15))
        console.log(q, this.lastdoc);
    }
    onSnapshot(q, (querySnapshot) => {
        const fbTasks = [] 
        this.lastdoc = querySnapshot.docs[querySnapshot.docs.length - 1]
            console.log(this.lastdoc); 
        querySnapshot.forEach((doc) => {
                const task = {
                    id: doc.id,
                    title: doc.data().title,
                    priority: doc.data().priority,
                    status: doc.data().status,
                    desc: doc.data().desc
                }
                fbTasks.push(task)
        })
            this.tasks = fbTasks
            this.spinnerShow = false
    })
}

I attempted to fetch the snapshot of the last document on the table from Firebase and then utilize the startAfter method when clicking the button to retrieve data from the last document obtained. However, it encountered an error:

Function startAfter() called with invalid data. Unsupported field value: undefined

and only the code within the else block executes

Answer №1

After delving deep into the firebase documentation and experimenting with the getDocs method, I successfully managed to tackle this issue on my own. By utilizing the startAfter method along with getting the snapshot of the last document on the page, I was able to retrieve the next set of data seamlessly. Take a look at the implementation below:

async fetchNextData(){
        this.showLoader = true;
        const docSnapshots = await getDocs(this.todosCollectionQuery);

        // Retrieve the last visible document
        const lastDoc = docSnapshots.docs[docSnapshots.docs.length-1];
        console.log("last", lastDoc);

        // Create a new query starting from this document
        const nextQuery = query(this.todosCollectionRef, orderBy("date", "desc"), startAfter(lastDoc), limit(10));

        onSnapshot(nextQuery, (querySnap) => {
            const tasksArray = [];
            querySnap.forEach((doc) => {
                const task = {
                    id: doc.id,
                    title: doc.data().title,
                    priority: doc.data().priority,
                    status: doc.data().status,
                    desc: doc.data().desc
                };
                tasksArray.push(task);
            });
            
            this.tasksList = tasksArray;
            this.showLoader = false;
        });
    }

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

In search of the most recent content inputted into a textarea

I'm facing an issue with a textarea that I have on my webpage. The problem arises when I select values from an autocomplete field and then try to update the textarea with these selected values. For instance, if I enter the characters 'a', & ...

Utilizing the same uuid twice along with Vuex and the unique identifier generation tool uuidv4

Within my vuex store, there is a function to create a post. This function generates a json Object containing a unique uuid using uuidv4(). However, I have noticed that if I execute the function multiple times, the uuid remains the same each time (unless I ...

Issues with method invocation in jQuery's .ajax requestI am having

After reading this Stack Overflow post, I now understand how to retrieve a return value from an AJAX call: function GetIsDataReady(input) { $.ajax({ url: "http://www.blah.com/services/TestsService.svc/IsDataReady", ...

Guide on triggering Bootstrap 4 modal to open on initial click with Vue.js

I have a component that I'm trying to load data from an API into a modal. The data loads correctly, but the modal only opens on the second click. The first click doesn't work. However, after opening and closing the modal once, it opens again. But ...

Guide on displaying React Native code within a React app on a web browser

Instead of creating media queries in my website built with React.JS or Next.JS and an app in React Native, can I display the entire app UI and functionality on mobile and tablet viewports? Please note that my inquiry is not related to code sharing. My ex ...

HTML steps for smooth scrolling to the top and bottom of a list

My HTML contains a vertical list with top and bottom arrows positioned nearby. I am looking to implement a function where clicking on the top arrow will move the list up gradually, and clicking on the bottom arrow will move the list down step by step. Belo ...

Vue-CLI project encountering issue with './node_modules/fsevents/fsevents.node' file

Today I ran into an issue with my Argon Vue.js project. When attempting to execute the 'npm run serve' command, the following error message was displayed: ERROR Failed to compile with 1 errors ...

Every file downloaded through the iframe is automatically stored in a designated server folder

Is it possible for my website to have an iframe that enables users to browse the web, and when they click on a download button on any external website, the file can be saved directly to a specific folder on my server instead of their own computer? I'm ...

Transfer various field values to jQuery

I am looking to send multiple field values to jQuery for validation, but currently only receiving the value of the changed field. How can I pass both field values to jQuery? Enter some text: <input type="text" name="txt1" value="Hello" onchange="myF ...

How to access and target $(this) in nested for each loops using jQuery

I am currently grappling with the issue of targeting each "$(this)" equivalent within nested foreach loops while iterating through a list of items. Let me illustrate my problem with an example: $('li').each(function(){ // My understandin ...

Exploring the intricacies of node streams and vinyl-fs

Experiencing a puzzling issue and unsure of the root cause. It's possible that my knowledge of node streams or vinyl-fs is lacking in some areas. Here's the scenario: I am creating various scripts to be used with gulp. For example, one script ...

How can I identify when a browser window is maximized using JavaScript or CSS?

I am currently working on a dashboard designed for static display on large monitors or TVs for clients. My main goal is to implement CSS styling, specifically a snap-scroll feature, but only when the display is in 'fullscreen' or 'maximized& ...

An excellent user interface that enables the user to easily reset a field to its original default value

Within my web-based application, users have the ability to customize values in specific textboxes. If they choose not to customize a value, the system will default to a predetermined option. I am looking to incorporate a feature that allows users to easil ...

Creating a JavaScript/jQuery array containing values from multiple input fields

Having trouble figuring out a simple question. I want to create a JavaScript array of input values, but can't seem to get the code right. Below is the HTML: <input class="email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Is there a way to determine when a Telegram web app specifically designed for bots has been shut down?

I have created a Telegram bot that opens a web app, whether through an inline button, keyboard, or link. Once the user completes the tasks in the web app, they can close it using the "close" button instead of any button within the web app that I can track. ...

Integrate a PHP link into a Gatsby/React project

I've been attempting to connect my contact form page, contactpage.php, with my Gatsby application. In the navigation bar (found in the Components folder), I've added the following code: <div> <a className="int_link_about" ...

Modifying the Vuex state triggers automatic updates to the LokiJS database. Wondering why? Discover the connection between Vuex

I am currently facing an issue with my app workflow. It involves retrieving data from an API backend and storing it in client storage using LokiJS, which results in thousands of data entries in client collections. To manage the state of my app, I utilize V ...

"Troubleshoot: Issue with React's useState hook not correctly updating state within an

I'm running into an issue with updating state using the useState hook in a React functional component. The problem arises when I have an async function (getPalettesPosition) that fetches data based on the current state (paletteFilters). Despite confir ...

"Switching out elements and tallying up values in an array

I am working with an array of identifiers for items var names = ['1','2', '1', '3']; Using these ids, I send an ajax request to retrieve the name associated with each id and replace it accordingly; var names = [ ...

Is it possible to invoke a PHP function from JavaScript using AJAX?

I have a JavaScript function that is triggered when I perform an action, and I want to call a PHP function. I understand that I need to use AJAX for this purpose, but I am unsure of the exact steps to achieve it. I have been learning about AJAX, but haven& ...