skip to Main Content

when performing Cloud Firestore compound queries with startAfter the result seems indefinite how do I know when I get to the last item in my collection and stop rendering.

this is the code that queries my data

const first = firebase.firestore().collection('dummy').doc('data').collection('test')
    .orderBy('createdAt').limit(1)
  
   const snapshot = await first.get();

  const last = snapshot.docs[snapshot.docs.length - 1]

  const next = firebase.firestore().collection('dummy').doc('data').collection('test')
    .orderBy('createdAt').startAfter(last.data().createdAt).limit(1)

   next.get().then((snapshot) => {

    let items = snapshot.docs.map(doc => {
    const data = doc.data();
    const id = doc.id;

    setType(data.type)

     return{id, ...data }
   })
  console.log(items)
  setNewOrder(items);
})

2

Answers


  1. how do I know when I get to the last item in my collection and stop rendering

    You have to keep paginating documents until you receive no more. There is no other flag or signal for the end of the result set.

    Login or Signup to reply.
  2. The problem might be here:

    startAfter(last.data().createdAt)
    

    If you have multiple documents with the same value for createdAt, this clause is not going to necessarily giving you the correct cursor document.

    Instead, consider passing the entire document to the startAfter, so that Firestore can use the full information in there to find the cursor document:

    startAfter(last)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search