user2828442
user2828442

Reputation: 2515

Fetch records from Firestore for pagination - Ionic/Angular

I am trying as per the docs to fetch first 25 records from Firestore like this.

Note: my requirement is to fetch the first 25 records which I am trying using current25 = documentSnapshots.docs; , it is not returning me the array of 25 records.

var first = db.collection("cities")
        .orderBy("population")
        .limit(25);

return first.get().then(function (documentSnapshots) {

// *** I am stuck here as I am not getting the array ***
var current25 = documentSnapshots.docs;
  console.log(current25);
  // 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 25 cities.
  var next = db.collection("cities")
          .orderBy("population")
          .startAfter(lastVisible)
          .limit(25);
});

Upvotes: 0

Views: 99

Answers (1)

Nibrass H
Nibrass H

Reputation: 2487

You can't return a promise because you are not giving enough time to the promise to be resolved. In order to solve your issue, you have to make your function async and await the promise to get the documents.

async function yourfunction(...){

   var first = db.collection("cities")
        .orderBy("population")
        .limit(25);

   const documentSnapshots = await first.get();


   var current25 = documentSnapshots.docs;
   console.log(current25);
   // 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 25 cities.
   var next = db.collection("cities")
        .orderBy("population")
        .startAfter(lastVisible)
        .limit(25);

   return "What you want to return";
}

Upvotes: 1

Related Questions