Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloud Firestore: listen for new documents in a collection and load them

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.

like image 799
andersamer Avatar asked Dec 07 '17 04:12

andersamer


People also ask

How do I listen to changes on firestore?

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.

How do I get a random document in a collection firestore?

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 .


1 Answers

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

like image 172
Frank van Puffelen Avatar answered Oct 06 '22 07:10

Frank van Puffelen