Firebase

How to implement Firebase Cloud Firestore pagination?

Discover how to handle large datasets effortlessly with Firebase Cloud Firestore pagination. Explore tips like using query limits and cursors, plus more tricks.

Developer profile skeleton
a developer thinking

Overview

Implementing pagination in Firebase Cloud Firestore means handling large chunks of data, by splitting it into smaller, easy-to-handle pieces. The key ideas to grasp are using query cursors and the limit() function to fetch data in bite-sized portions. First, figure out the page size you want. Then, grab the first batch of documents. For the pages that come next, use the startAfter() or startAt() methods, which depend on the last document from the previous batch. This technique ensures smooth browsing and reduces the strain on resources. Know these fundamentals well, and your Firestore apps will run faster and smoother for everyone involved.

Get a Free No-Code Consultation
Meet with Will, CEO at Bootstrapped to get a Free No-Code Consultation
Book a Call
Will Hawkins
CEO at Bootstrapped

How to implement Firebase Cloud Firestore pagination?

Step 1: Set Up Firebase

  • Start by creating or using an existing Firebase project in the Firebase Console.
  • Head over to the Firestore Database section and set up your database.
  • Add some data to Firestore that you'll use for pagination.

Step 2: Initialize Firebase in Your Application

  • First, install the Firebase SDK in your project.
    npm install firebase
    
  • Then, initialize Firebase in your application code.
    ```
    import firebase from 'firebase/app';
    import 'firebase/firestore';

const firebaseConfig = {
// Your Firebase config object
};

if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}

const db = firebase.firestore();


<div style="color:#0065ff"><h3>Step 3: Define a Page Size Variable</h3></div>

- Set a constant variable for the number of documents to retrieve per page.

const PAGE_SIZE = 10;


<div style="color:#0065ff"><h3>Step 4: Fetch the First Page</h3></div>

- Create a function to fetch the first set of documents from Firestore.

async function fetchFirstPage() {
const firstPageQuery = db.collection('yourCollection')
.orderBy('yourField')
.limit(PAGE_SIZE);
const documentSnapshots = await firstPageQuery.get();

// Store the last document for future use
const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];

// Use the data as required
const data = documentSnapshots.docs.map(doc => doc.data());
console.log(data);

return lastVisible;
}

- Call the function.

let lastVisible = await fetchFirstPage();


<div style="color:#0065ff"><h3>Step 5: Fetch the Next Page</h3></div>

- Create a function to fetch the subsequent pages.

async function fetchNextPage(lastVisible) {
const nextPageQuery = db.collection('yourCollection')
.orderBy('yourField')
.startAfter(lastVisible)
.limit(PAGE_SIZE);
const documentSnapshots = await nextPageQuery.get();

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

const data = documentSnapshots.docs.map(doc => doc.data());
console.log(data);

return lastVisible;
}

- Call the function to get the next page.

lastVisible = await fetchNextPage(lastVisible);


<div style="color:#0065ff"><h3>Step 6: Handling Edge Cases</h3></div>

- Check if there are no more documents to fetch.

async function fetchNextPage(lastVisible) {
const nextPageQuery = db.collection('yourCollection')
.orderBy('yourField')
.startAfter(lastVisible)
.limit(PAGE_SIZE);
const documentSnapshots = await nextPageQuery.get();

if (documentSnapshots.empty) {
console.log('No more documents to fetch');
return null; // No more pages
}

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

const data = documentSnapshots.docs.map(doc => doc.data());
console.log(data);

return lastVisible;
}


<div style="color:#0065ff"><h3>Step 7: Optional - Implement Previous Page Functionality</h3></div>

- Store the last visible documents for each fetched page to enable navigating back to the previous pages.
- Create a function to fetch the previous page using stored last visible documents from prior pages.

let pageCursors = []; // Will contain the last documents of each page for navigation

async function fetchFirstPage() {
const firstPageQuery = db.collection('yourCollection')
.orderBy('yourField')
.limit(PAGE_SIZE);
const documentSnapshots = await firstPageQuery.get();

const lastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];
pageCursors.push(null); // No previous page for the first page

const data = documentSnapshots.docs.map(doc => doc.data());
console.log(data);

return lastVisible;
}

async function fetchNextPage(lastVisible) {
const nextPageQuery = db.collection('yourCollection')
.orderBy('yourField')
.startAfter(lastVisible)
.limit(PAGE_SIZE);
const documentSnapshots = await nextPageQuery.get();

if (documentSnapshots.empty) {
console.log('No more documents to fetch');
return lastVisible;
}

const newLastVisible = documentSnapshots.docs[documentSnapshots.docs.length - 1];
pageCursors.push(lastVisible); // Store the current lastVisible for possible back navigation

const data = documentSnapshots.docs.map(doc => doc.data());
console.log(data);

return newLastVisible;
}

async function fetchPreviousPage(currentPageIndex) {
if (currentPageIndex <= 0) {
console.log('Already on the first page');
return;
}

const lastVisible = pageCursors[currentPageIndex - 1]; // Get the lastVisible from the previous page
pageCursors.pop(); // Remove the last page cursor as we navigate back

const previousPageQuery = db.collection('yourCollection')
.orderBy('yourField')
.endBefore(lastVisible) // Use endBefore to move back
.limitToLast(PAGE_SIZE);
const documentSnapshots = await previousPageQuery.get();

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

const data = documentSnapshots.docs.map(doc => doc.data());
console.log(data);

return newLastVisible;
}


// Usage Example
let currentPageIndex = 0;
let lastVisible = await fetchFirstPage();

document.getElementById('nextButton').addEventListener('click', async () => {
currentPageIndex++;
lastVisible = await fetchNextPage(lastVisible);
});

document.getElementById('previousButton').addEventListener('click', async () => {
currentPageIndex--;
lastVisible = await fetchPreviousPage(currentPageIndex);
});


Explore more Firebase tutorials

Complete Guide to Firebase: Tutorials, Tips, and Best Practices

Explore our Firebase tutorials directory - an essential resource for learning how to create, deploy and manage robust server-side applications with ease and efficiency.

Why are companies choosing Bootstrapped?

40-60%

Faster with no-code

Nocode tools allow us to develop and deploy your new application 40-60% faster than regular app development methods.

90 days

From idea to MVP

Save time, money, and energy with an optimized hiring process. Access a pool of experts who are sourced, vetted, and matched to meet your precise requirements.

1 283 apps

built by our developers

With the Bootstrapped platform, managing projects and developers has never been easier.

hero graphic

Our capabilities

Bootstrapped offers a comprehensive suite of capabilities tailored for startups. Our expertise spans web and mobile app development, utilizing the latest technologies to ensure high performance and scalability. The team excels in creating intuitive user interfaces and seamless user experiences. We employ agile methodologies for flexible and efficient project management, ensuring timely delivery and adaptability to changing requirements. Additionally, Bootstrapped provides continuous support and maintenance, helping startups grow and evolve their digital products. Our services are designed to be affordable and high-quality, making them an ideal partner for new ventures.

Engineered for you

1

Fast Development: Bootstrapped specializes in helping startup founders build web and mobile apps quickly, ensuring a fast go-to-market strategy.

2

Tailored Solutions: The company offers customized app development, adapting to specific business needs and goals, which ensures your app stands out in the competitive market.

3

Expert Team: With a team of experienced developers and designers, Bootstrapped ensures high-quality, reliable, and scalable app solutions.

4

Affordable Pricing: Ideal for startups, Bootstrapped offers cost-effective development services without compromising on quality.

5

Supportive Partnership: Beyond development, Bootstrapped provides ongoing support and consultation, fostering long-term success for your startup.

6

Agile Methodology: Utilizing agile development practices, Bootstrapped ensures flexibility, iterative progress, and swift adaptation to changes, enhancing project success.

Yes, if you can dream it, we can build it.