Ali Fumagalli
Ali Fumagalli

Reputation: 289

How to paginate filtered results with Firebase?

I have a list of customers saved in a firestore collection built like this:

Now, i want to create a customers archive page with some filters (by name, by category, by city, by country).

I would like to show results 20 at a time with an infinite scroll system.

For example I could request all the customers of a certain city and then I could add a second filter (by category) and mix them together.

What is the best way to build this system?

Thanks! :)

Upvotes: 0

Views: 105

Answers (1)

Renaud Tarnec
Renaud Tarnec

Reputation: 83093

You just need to paginate your query using the technique described in the documentation.

For example, with your last example:

var first = db.collection("customers")
        .where('city', '==', 'city1')
        .where('category', '==', 'category1')
        .limit("20");

return first.get().then(function (documentSnapshots) {
  // Get the last visible document
  var lastVisible = documentSnapshots.docs[documentSnapshots.docs.length-1];
  console.log("last", lastVisible);

  // Construct a new query starting at this document,
  // get the next 20 customers.
  var next = db.collection("customers")
        .where('city', '==', 'city1')
        .where('category', '==', 'category1')
        .startAfter(lastVisible)
        .limit("20");

});

Upvotes: 2

Related Questions