Firestore Chat App - Build Messages Home Page
I have a Flutter chat app with Firestore RTDB backend:
messages (collection)
message_1 (document)
chat (collection)
chat_1 (document)
chat_2 (document)
users (array, document field)
user_id_1 (String)
user_id_2 (String)
user_info (map to store user info, like name, avatar etc)
message_2 (document)
chat (collection)
chat_1 (document)
chat_2 (document)
users (array, document field)
user_id_1 (String)
user_id_2 (String)
user_info (map to store user info, like name, avatar etc)
I want to create a home page where it shows all the chats a user is involved in, sorted by most recent, just like any normal chat app:
I know how to show the chats the user is involved in. Problem is, I don't know how to handle the sorting. There is one simple way to do this: each time a new message is sent, use a cloud function and update a field in the message document called lastSent
, then do orderBy('lastSent', descending: true)
in your query. The problem is, each time you send a message, you have to do two writes instead of one just to update this field. Is there a better way to handle this?
Note: My app is not solely a chat app, this is only part of the main app. Imagine a chat functionality similar to Airbnb, so the volume or frequency of chat messages may not be as large as Facebook messenger for example
Answer
The common solution is to do what you propose: store a latest_updated
timestamp in the document of each "chat room".
That indeed means that you'll need to do two writes instead of one. But on the other hand, you can now determine the correct ordering with by just reading the "chat room" documents, instead of having read individual messages under it.
Note that, while it is certainly possible to do this with Cloud Functions, this can also be done directly from the client. You can even catch the requirement in security rules that a client can only write a new message, if they also set the latest_updated
timestamp of the corresponding "chat room" document to the same value as the timestamp of the message, although this will incur the cost of one additional document read for each message you add.
Related Questions
- → How can I query Firebase for an equalTo boolean parameter?
- → How can I access nested data in Firebase with React?
- → Firebase simple blog (confused with security rules)
- → Removing item in Firebase with React, re-render returns item undefined
- → AngularJS Unknown Provider Error (Firebase & AngularFire)
- → How do you pass top level component state down to Routes using react-router?
- → "this" is null in firebase query function in reactjs
- → Angular Module Failed to Load
- → Multiple dex files define Lcom/google/android/gms/internal/zzrx;
- → Joining Firebase tables in React
- → How can I make add firepad to my reactjs project?
- → How to use Cloud Functions for Firebase to prerender pages for SEO?
- → React.js component has null state?