0

I am confused how to make pagination with realtime firestore query:

const subscriber = firestore()
        .collection('notifications')
        .doc(authenticatedUser.uid)
        .collection('notificationItems')
        .orderBy('createdDate', 'desc')
        .limit(5)
        .onSnapshot(response => {
          setNotifications(response.docs); // Settings all to app state

With this I receive realtime updates from firestore but how to append new data and continue to listen.
If I call this again then I get new subscriber.
Can somebody hint me just how to append new items and continue listening changes?

Just to be clear I am keeping reference to the last item from response and then use startAfter() to get next item I just don't know how to do the same with onSnapshot

1110
  • 7,829
  • 55
  • 176
  • 334
  • 2
    There seem to be quite some relevant hits when I [search for firestore realtime pagination](https://www.google.com/search?q=firestore+realtime+pagination), so that'd probably be a good page to start. Sorry for the non-answer, but pagination on a data set that changes in realtime is notoriously hard (believe me: we tried) as a general use-case. – Frank van Puffelen Aug 12 '22 at 17:53
  • Not sure what you mean by that edit: you should be able to pass a query with a `startAfter` condition to `onSnapshot` too. Doesn't that work for you? Any error? – Frank van Puffelen Aug 12 '22 at 17:53
  • This is for non constantly changing data liek notifications and chat messages those data never change but I need to listen for new but I can't load chat with 1000 message documents :) – 1110 Aug 12 '22 at 17:54
  • But if I call this function again then on each page I get new subscriber and I really need just one. Am I correct? – 1110 Aug 12 '22 at 17:55
  • Uhm... it depends.... :( If your data set is append-only, one options is to create a new query every time you need a new page, with a larger `limit`. If you have disk caching enabled/or attach the new `onSnapshot` before cancelling the previous one, this will only read the documents in the new page from the server. – Frank van Puffelen Aug 12 '22 at 18:00
  • This is how looks advanced paginated query. https://stackoverflow.com/a/70773801/6310260, but it is not perfect. – Mises Aug 12 '22 at 18:07

1 Answers1

0

If your data set is append-only, one option is to create a new query every time you need a new page, with a larger limit. You wouldn't actually need a startAfter clause when you do that.

So for the first page, you'd start with limit(5). Then for loading the second page, you use limit(10), and so on.

If you have disk caching enabled/or attach the new onSnapshot before cancelling the previous one, this will only read the documents in the new page from the server.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807