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
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.
The problem might be here:
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: