How to Build an Instant Messaging Feature for your React Native app using CometChat
Introduction
Intuitive and instant messaging features allow users to do more all in one place. CometChat is an in-app messaging platform with features like integrations and multiple build options that make it user-friendly for developers with varying skill sets.
CometChat also lets you add a user to user chat with no trouble, making it a great tool for Applications that are already working and would like to enhance their user experience.
In our article, we will learn how to integrate CometChat step by step while working on a React Native project. Let’s get started!
At White Prompt, we turn the what into how during the User Experience phase. We transition research into real-life solutions with creative application flows. At each step, we put on our “user hat” and check-in to ask questions. If you are searching for a next-level software development company that offers true end-to-end capabilities, White Prompt is ready to help you develop solutions. Contact us today to get your free consultation.
Requirements
To begin, let’s review the requirements necessary to build our application. You will need:
- A text editor. (e.g. Visual Studio Code, Notepad++, Sublime Text, Atom, or VIM)
- Node
- npm
- React-Native
Installation
To begin the installation process, you will need to register on CometChat and create a new app there. It offers a free tier so let’s start with that:
After creating your application, you will need to go to the Credentials section to record the App Id and the API key.
Now it’s time to add the CometChat dependency on your React Native app using the following command:
npm install @cometchat-pro/react-native-chat@3.0.2 --save
Also, in order to have the integration working you will also need to install Async-Storage package as follows:
npm install @react-native-async-storage/async-storage --save
Integration
For the integration process, you will need to initialize CometChat by using the init()
method which is usually added onto your App.jsx
file. We will be calling it with a setting object that will contain the information from our CometChat application.
const appSetting = new CometChat
.AppSettingsBuilder()
.subscribePresenceForAllUsers()
.setRegion(‘us’)
.build();
CometChat.init(Config.cometChatAppId, appSetting)
.then(() => console.log(‘Init completed’));
In order to build this setting object, the SDK will have an AppSettingBuilder
method that will let us do the job easily.
Here are a few items to note as we continue our development:
- As we have set the region to the US, we are using
setRegion
- The Config.cometChatAppId in your code needs to match your CometChat App Id. This step is very important before we continue with next steps.
Create, Login and Edit Users
Now you are able to register a user or login a user into the chat application. When your users have been identified in your system you can go ahead and register them on CometChat.
const authKey = 'AUTH_KEY';
const uid = 'userA';
const name = 'Kevin';
const user = new CometChat.User(uid);
user.setName(name);
CometChat.createUser(user, authKey).then(
user => {
console.log(“user created”, user);
}, error => {
console.log(“error”, error);
}
)
uid
and name
are mandatory so you will need to specify them. Your uid
is going to be the identifier of your user. It will end up being a string so keep that in mind if you are sending an int.
Important Note: uid
can be alphanumeric with an underscore and hyphen. Spaces, punctuation and other special characters are not allowed.
After User Creation, you will be ready to login using the login
method as seen here:
let UID = 'SUPERHERO1';
let authKey = 'AUTH_KEY';
CometChat.getLoggedinUser().then(
(user) => {
if(!user) {
CometChat.login(UID, authKey)
}
}
);
You only need to login the user one time per session. This is why we are using getLoggedinUser
to see if there is a user already logged in to follow in accordance.
In case you have a page to setup your profile, you will need to call the updateUser
method to keep your user information in sync on CometChat.
This is an example of how you can set/update a user avatar picture and some metadata that might be relevant in your mobile application:
const cometUser = new CometChat.User('userA');
cometUser.setName('newName'); //info that comes from your profile setup page
if (avatarUrl) {
//if user have set a profile picture on your app
//you will want to update it on CometChat as well
cometUser.setAvatar(avatarUrl);
}
//metadata is usefull to display extra information on a conversation list
//or to display on user information with no need of an extra BE call
cometUser.setMetadata(
JSON.stringify({
company: user.company,
title: user.title,
phone: user.phone,
email: user.email
})
);
CometChat.updateUser(cometUser, Config.cometChatAuthKey);
Creating and Retrieving a Conversation
For our next step, let’s assume that 2 users (userA and userB) are interacting in your mobile app and both already have their user created on the CometChat App. When interacting, we can have a new feature to send an instant message; we will use sendMessage
method. It will receive some arguments. The first argument is the uid
of the receiver; the second one is the text of the message; the third is the conversation type (on this case we are working on a user-to-user chat feature so it will be user
, but it can also be a group
.
//messageText may be the user input or also be a default initial message
//receiverUID on our example is going to be 'userB'
const textMessage = new CometChat.TextMessage(receiverUID, messageText, 'user');
CometChat.sendMessage(textMessage)
In order to retrieve conversations we are going to use the ConversationsRequestBuilder
method which will provide us with the list of conversations to record on our component.
Once you have the object of the
ConversationsRequest
class, you need to call thefetchNext()
method. Calling this method will return a list ofConversation
objects containing X number of users depending on the limit set.A Maximum of only 50 Conversations can be fetched at once.
The Conversation
Object consists of the following fields below:
conversationId: ID of the conversation.
conversationType: Type of conversation (user/group).
lastMessage: Last message the conversation.
conversationWith: User or Group object containing the details of the user or group.
unreadMessageCount: Unread message count for the conversation.
const [conversations, setConversations] = useState([]);
const getConversations = () => {
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
.setLimit(50)
.build();
conversationsRequest
.fetchNext()
.then((conversationList) => {
setConversations(conversationList);
})
}
useEffect(() => {
getConversations();
},[])
return (
<FlatList
data={conversations}
renderItem={({ item }) => (
<ConversationItemRow conversation={item}/>
)}
/>
)
Getting Old Messages and Listening to a Conversation
Once the user selects a conversation from the FlatList, we will want to retrieve that single conversation’s previous messages to display the entire exchange.
For this to happen, we will use messageRequestBuilder
and its fetchPrevious()
.
const getMessagesFunction = () => {
const messagesRequest = new CometChat.MessagesRequestBuilder()
.setUID(userUid)
.setLimit(100)
.build();
messagesRequest.fetchPrevious().then(
(res) => {
setMessages(res); //store messages to display on conversation
}
)
}
You can also use CometChat.markAsRead(message)
to let CometChat know about the read status of this message.
Now that we have the conversation being rendered, we will want to add a listener for it to behave like it is; a realtime conversation. In order to do that we will use addMessageListener
to let our code know what to do once it receives a new message. For this case, we will force the pull of messages so we will be rendering the full conversation every time a new message is received.
useEffect(() => {
const listenerID = `MESSAGE_LISTENER_KEY${uniqueId}`;
navigation.addListener(‘focus’, () => {
CometChat.addMessageListener(
listenerID,
new CometChat.MessageListener({
onTextMessageReceived: () => getMessagesFunction(),
})
);
});
//don't forget to remove the listener on unmount
navigation.addListener(‘blur’, () =>
CometChat.removeMessageListener(listenerID)
);
}, []);
At this point in our process, you have completed the full cycle of a conversation. Congratulations!
Conclusion
With these few steps you have been able to successfully connect and start using CometChat on your application. Let’s review what we have learned.
Create Conversation Between Users
Your app may let the active user enter the text of the initial message or you can display a default message to let the receiver know about someone trying to contact him.
Retrieve and List Conversations
Existing conversations will let the user navigate properly. You can also use a CometChat user avatar and metadata to display extra information (company, email, user title, etc).
See Old Messages and Listen for New Ones
This will let the user read all messages, and you can add more fetch actions to check if a conversation has prior messages to display once the user has scrolled enough.
We think and we do!
Working with us at White Prompt can lead to great outcomes for your project or application. Do you have a business that requires an efficient and powerful data architecture to succeed? Looking for a software development agency to make it happen? Get in touch with us at White Prompt today!