Need to implement two interfaces:
function subscribeChatRoom(orderId, onMessage)function sendMessage(orderId, message)
Message:
- id (string)
- created_at (timestamp)
- message: (string)
- sender_id: (string)
These messages will be stored inside the orders collection. Specifically, each order document in the collection will have a subcollection called chat.
Collection path: orders > order ID > chat > message ID.
To set up the subscription, get the firebase collection ref and attach an onSnapshot listener.
import firestore from '@react-native-firebase/firestore';
const COLLECTION_NAME = 'orders';
const SUBCOLLECTION_NAME = 'chat';
// add this to the implementation of
// subscribeChatRoom
const db = firestore();
const chatRef = db.collection(`${COLLECTION_NAME}/${orderId}/${SUBCOLLECTION_NAME}`);
chatRef.onSnapshot(snapshot => {
// do something on collection change (add / remove docs)
const docs = snapshot.docs;
// call onMessage
});To send message, you simply add a new doc to the subcollection
import firestore from '@react-native-firebase/firestore';
import {getCurrentUser} from '~/services/user';
const COLLECTION_NAME = 'orders';
const SUBCOLLECTION_NAME = 'chat';
// add this inside the sendMessage implementation
const db = firestore();
const chatRef = db.collection(`${COLLECTION_NAME}/${orderId}/${SUBCOLLECTION_NAME}`);
chatRef
.doc() // creates a new doc, let the SDK generates the ID
.set({
created_at: new Date(),
message: 'my message',
sender_id: getCurrentUser().uid,
});https://github.com/jagocoffee/jago-consumer-app/pull/28