I am using firestore for my chat application
I have 2 tabs, first one is for to display all registered users and another second tab to display all users I've chatted with.
i have created 2 collections in firestore
i have combined 2 users id to identify sender and receiver and stored it in messages.
Code:
1. //get all registered users
const querySanp = await firestore()
.collection('users')
.where('uid', '!=', user.uid)
.get();
const allusers = querySanp.docs.map(docSnap => docSnap.data());
setUsers(allusers);
2. //get all registered users
const docid = uid > user.uid ? user.uid + '-' + uid : uid + '-' + user.uid;
const messageRef = firestore()
.collection('chatrooms')
.doc(docid)
.collection('messages')
.orderBy('createdAt', 'desc');
const unSubscribe = messageRef.onSnapshot(querySnap => {
const allmsg = querySnap.docs.map(docSanp => {
const data = docSanp.data();
if (data.createdAt) {
return {
...docSanp.data(),
createdAt: docSanp.data().createdAt.toDate(),
};
} else {
return {
...docSanp.data(),
createdAt: new Date(),
};
}
});
setMessages(allmsg);
});
How to get users i have chat with ?
You can create a collection :
Conversations: {
user1,
user2
}
And in your messages collection:
messages : {
conversationId,
sender,
receiver
}
So you in your app (I suppose you have a screen chats), you just get all the conversations where you are user1 or user2.