/firebase-tutorials

How to paginate Firestore results?

Discover how to paginate Firestore results in your Firebase app with step-by-step instructions, code examples, and cursor management for smooth navigation.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to paginate Firestore results?

 

Step 1: Setup Firebase in Your Project

 

Ensure you have Firebase integrated into your project. If you haven't done so yet, visit the Firebase Console and add your project. Follow the instructions to add Firebase to your app. Make sure to include Firestore in your setup.

 

Step 2: Initialize Firestore

 

Once Firebase is set up, initialize Firestore in your app. Below is an example for initializing Firestore in a JavaScript project.

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

// Your web app's Firebase configuration
const firebaseConfig = {
  apiKey: 'YOUR_API_KEY',
  authDomain: 'YOUR_AUTH_DOMAIN',
  projectId: 'YOUR_PROJECT_ID',
  storageBucket: 'YOUR_STORAGE_BUCKET',
  messagingSenderId: 'YOUR_MESSAGING_SENDER_ID',
  appId: 'YOUR_APP_ID'
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

 

Step 3: Define Pagination Parameters

 

Decide on the number of items you want to display per page and store this value in a variable.

const pageSize = 10; // Number of documents to retrieve per page

 

Step 4: Retrieve the First Page of Results

 

Use Firestore's limit function to retrieve the first set of results from a collection.

import { collection, getDocs, query, orderBy, limit } from 'firebase/firestore';

async function getFirstPage() {
  const q = query(
    collection(db, 'YOUR_COLLECTION_NAME'),
    orderBy('YOUR_FIELD_NAME'),
    limit(pageSize)
  );

  const documentSnapshots = await getDocs(q);

  // Store the last document as a cursor for the next page
  const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];

  return { documentSnapshots, lastVisible };
}

 

Step 5: Retrieve the Next Page of Results

 

To paginate, use the startAfter function with your stored last document as a cursor.

import { startAfter } from 'firebase/firestore';

async function getNextPage(lastVisible) {
  const q = query(
    collection(db, 'YOUR_COLLECTION_NAME'),
    orderBy('YOUR_FIELD_NAME'),
    startAfter(lastVisible),
    limit(pageSize)
  );

  const documentSnapshots = await getDocs(q);

  // Update the cursor
  const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];

  return { documentSnapshots, lastVisible };
}

 

Step 6: Handle Previous Page Functionality

 

Firestore does not support native backward pagination. However, you can manage an array of cursors or use additional libraries to simulate this feature. Here’s a simple approach:

const cursors = []; // Store cursors for backward navigation

async function getNextPage(lastVisible) {
  // Push current lastVisible to cursors array
  cursors.push(lastVisible);

  const q = query(
    collection(db, 'YOUR_COLLECTION_NAME'),
    orderBy('YOUR_FIELD_NAME'),
    startAfter(lastVisible),
    limit(pageSize)
  );

  const documentSnapshots = await getDocs(q);

  const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];

  return { documentSnapshots, lastVisible };
}

function getPreviousPage() {
  if (cursors.length < 2) return null; // No previous page

  // Remove the last cursor
  cursors.pop();

  // Get the last cursor for current navigation step
  const lastCursor = cursors[cursors.length - 1];

  return getNextPage(lastCursor);
}

 

Step 7: Display Results in the UI

 

Once you have the document snapshots from Firestore, map through them and display the data as needed in your application's UI.

function displayResults(documentSnapshots) {
  documentSnapshots.forEach(doc => {
    console.log(doc.id, " => ", doc.data());
  });
}

 

Now you have a working pagination system using Firestore, displaying a set number of results and allowing navigation through pages. Adjust the collection names, field names, and conditions according to your use case.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022