I am making a messaging app using Firebase and Cloud Firestore. I have a collection called "messages" that contains documents for each message. My main goal is to listen to that collection for new documents and load them without reloading all the documents in the collection.
EDIT: In a nutshell, I want the client to load messages saved by other clients.
You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.
An easy way to grab random documents is get all the posts keys into an array ( docA , docB , docC , docD ) then shuffle the array and grab the first three entries, so then the shuffle might return something like docB , docD , docA .
That depends on what defines when a document is "new" for you.
If "new" means "created after now()", then you need to have a created
timestamp in your document and query to start at now()
. That's pretty similar to what David explained here for the Firebase Realtime Database: How to only get new data without existing data from a Firebase?
If "new" means "documents this user hasn't loaded before", you will need to track the latest document they've seen, and start a query at that document. Kato explained a similar model for the Firebase Realtime here: Firebase child_added without loading all data first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With