React Native Chat using firebase
In this article, I will explain about React Native chat app using firebase and react-native-gifted-chat.
What are the complication things we normally face when creating a chat application using firebase?
The very first one is the data structure of firebase for a chat application.
The above picture is the example of the group chat. I this case I mean group chat is, there is one common chat room, So whoever use this application can chat with others.
Firebase function for create chatGroup
export const sendGroupMsg = (message) => {
return db.collection('groupChat').add(message);
};
No need to worry about the front view. There is one plugin called gifted chat in react-native. Gifted chat provide good UI design
It also generates send a message format. So we just pass our message only.
this.setState({
messages: [
{
_id: 1,
text: 'Hello developer',
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
avatar: 'https://placeimg.com/140/140/any'
}
}
]
});
The above code is just an example. We should give our data in this case.
Firebase fetch messages
import firebase from 'react-native-firebase';
const db = firebase.firestore();
db.collection('groupChat').onSnapshot(function(doc) {
console.log(doc.docs);
});
The above one is applicable for one user can chat with multiple users.
how we handle Individual chat?
For example User A chat with User B and User A chat with User C individually.
We should think about the firebase data structure.
The above picture explains about the data structure of firestore.
In this case, we create a document for two or more users.
Our doc id is chatterId and chateeId. In below code, we merge two ids and create a new one. we store all data under the chat Id.
chatID = () => {
const chatterID = this.props.authUser.uid;
const chateeID = this.chateeUID;
const chatIDpre = [];
chatIDpre.push(chatterID);
chatIDpre.push(chateeID);
chatIDpre.sort();
return chatIDpre.join('_');
};
Send a message to firestore.
export const sendChatMessage = (chatID, chat) => {
return db
.collection('messages')
.doc(chatID)
.collection('chats')
.add(chat);
};
Receive the messages from firebase.
const db = firebase.firestore();
db.collection('messages')
.doc(chatID)
.collection('chats')
.orderBy('createdAt', 'desc')
.onSnapshot(function(doc) {
console.log(doc.docs);
});
In above code get messages whenever changes happen in firestore. When we come, individual chat we should send or get data using chatId only.
Thank You for reading……..