Firebase : How To Paginate - A Quick Guide

Pagination, or “How to Fetch a Data Set in Parts”

You want to provide a quick initial set of data to your Firebase user, say the first 5 blog posts. If they want more, you can serve up what is needed, always being considerate of their waiting time and network data usage.

This is a great design pattern, because it is optimising the right thing at the right time. At the start, you care most about speed, and giving the user something to work with. Then you care about giving them more of what they want.

It is often called “Pagination”, or “Chunking”.

In this article, I explain how to do this in Firebase.

Step 0: Design the Firebase Data

For this pattern to work, the data set must have a concept of order.

It does not matter how you achieve this order.

One easy option is to use Firebase’s push(). This creates a key based on a timestamp so the order will be “order of creation”.

An alternative is to use a key of your own.

**Step 1: Deliver the Initial Chunk

**

First, we want to show the first 5 entries in the array.

So, on your request to Firebase to get the data, you say:

“I want the data in order.” => use orderByKey “I only want 5 entries.” => use limitToFirst: 5

**Step 2: Deliver the Next Batch

**

Then, to get the next 10, you need the key of the last one you have already retrieved. Your request says:

“I want the data in order” => orderByKey “I want to start after the first 5” => startAt: “I only want 10 entries” => limitToFirst: 10

And that’s it! A very quick guide to how you can easily paginate your data in Firebase.

How you use the orderByKey, startAt, limitToFirst options on your Firebase request depends on your choice of client library. But the principle is the same whichever you choose.

There are various choices you can use for how to order: by key, by value, but I hope this is a useful starting point. Please let me know if it is not clear.

Here’s the official Firebase documentation for this:

  * [for web apps](https://firebase.google.com/docs/database/web/retrieve-data#sorting_and_filtering_data)
  * [for Android apps](https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query)
  * [for IOS apps](https://firebase.google.com/docs/reference/ios/firebasedatabase/interface_f_i_r_database_query)