Home > Back-end >  startAfter function always display the same data
startAfter function always display the same data

Time:07-21

I'm beginner to firestore. My query always give the same data independently of the value i pass into startAfter() function.

here's code:

    const fetchMore = async () => {
        const q = query(
            collection(db, 'chat-messages'),
            orderBy('createdAt', 'asc'),
            startAfter(23),
            limit(5),
        );

        const querySnapshot = await getDocs(q)

        querySnapshot.forEach(doc => {
            console.log(doc.data())
        })
    }

Thanks for reading and helping! Have a nice day

enter image description here

here's the console.log

CodePudding user response:

I'm not sure what type the data in your startAt field is, but I guess it's a date or a Firestore Timestamp.

Pagination in Firestore is not based on numeric offsets, as you may be used to from other databases, but instead is based on so-called cursor objects: knowing the values and/or ID of the document you want to start after.

So you'll need to pass in the timestamp that you want to start after, not the number of documents you want to skip. So for example, to get all documents with a createdAt after now, you could do:

startAfter(Timestamp.now())

For more on this way of pagination, see the documentation on paginating data with query cursors.

  • Related