diff --git a/docs.json b/docs.json index 6fe2a0c07..fb5f4a6a3 100644 --- a/docs.json +++ b/docs.json @@ -2954,7 +2954,14 @@ "pages": [ "sdk/react-native/resources-overview", "sdk/react-native/real-time-listeners", - "sdk/react-native/push-notification-setup", + { + "group": "Push Notifications", + "pages": [ + "notifications/react-native-push-notifications-android", + "notifications/react-native-push-notifications-ios" + ] + }, + "sdk/react-native/push-notification-html-stripping", "sdk/react-native/upgrading-from-v3" ] }, @@ -5156,7 +5163,7 @@ "notifications/ios-apns-push-notifications", "notifications/ios-fcm-push-notifications", "notifications/flutter-push-notifications-android", - "notifications/flutter-push-notifications-ios", + "notifications/flutter-push-notifications-ios", "notifications/react-native-push-notifications-android", "notifications/react-native-push-notifications-ios", "notifications/web-push-notifications" @@ -5859,62 +5866,62 @@ { "source": "/notifications/push-notification-extension-overview", "destination": "/notifications/push-notification-extension-legacy" - }, + }, { "source": "/notifications/push-notification-extension-legacy", "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/web-push-notifications-legacy", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/web-push-notifications-legacy", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/android-push-notifications-legacy", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/android-push-notifications-legacy", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/android-connection-service", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/android-connection-service", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/ios-fcm-push-notifications-legacy", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/ios-fcm-push-notifications-legacy", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/ios-apns-push-notifications-legacy", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/ios-apns-push-notifications-legacy", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/flutter-push-notifications", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/flutter-push-notifications", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/react-native-push-notifications-legacy", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/react-native-push-notifications-legacy", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/capacitor-cordova-ionic-push-notifications", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/capacitor-cordova-ionic-push-notifications", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/mute-functionality", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/mute-functionality", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/token-management", - "destination": "/notifications/push-notifications-extension-legacy" + "source": "/notifications/token-management", + "destination": "/notifications/push-notifications-extension-legacy" }, { - "source": "/notifications/email-notification-extension", - "destination": "/notifications/email-notifications-extension-legacy" + "source": "/notifications/email-notification-extension", + "destination": "/notifications/email-notifications-extension-legacy" }, { - "source": "/notifications/sms-notification-extension", - "destination": "/notifications/sms-notifications-extension-legacy" + "source": "/notifications/sms-notification-extension", + "destination": "/notifications/sms-notifications-extension-legacy" }, { - "source": "/notifications/react-native-push-notifications", - "destination": "/notifications/react-native-push-notifications-android" + "source": "/notifications/react-native-push-notifications", + "destination": "/notifications/react-native-push-notifications-android" } ], "integrations": { diff --git a/images/xcode-embedd-extensions-debug.png b/images/xcode-embedd-extensions-debug.png new file mode 100644 index 000000000..3e58ff79a Binary files /dev/null and b/images/xcode-embedd-extensions-debug.png differ diff --git a/images/xcode-notificaion-service-maintarget-screenshot.png b/images/xcode-notificaion-service-maintarget-screenshot.png new file mode 100644 index 000000000..ed147d9df Binary files /dev/null and b/images/xcode-notificaion-service-maintarget-screenshot.png differ diff --git a/images/xcode-notificaion-service-screenshot.png b/images/xcode-notificaion-service-screenshot.png new file mode 100644 index 000000000..c974c7c67 Binary files /dev/null and b/images/xcode-notificaion-service-screenshot.png differ diff --git a/images/xcode-objectiveC.png b/images/xcode-objectiveC.png new file mode 100644 index 000000000..12119b0ef Binary files /dev/null and b/images/xcode-objectiveC.png differ diff --git a/sdk/react-native/additional-message-filtering.mdx b/sdk/react-native/additional-message-filtering.mdx index 92416031c..04addae46 100644 --- a/sdk/react-native/additional-message-filtering.mdx +++ b/sdk/react-native/additional-message-filtering.mdx @@ -1,11 +1,36 @@ --- title: "Additional Message Filtering" +description: "Learn how to use MessagesRequestBuilder to filter and fetch messages by conversation, type, category, tags, timestamps, and more in the CometChat React Native SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Fetch messages for a user conversation +let request = new CometChat.MessagesRequestBuilder().setUID("UID").setLimit(50).build(); + +// Fetch messages for a group conversation +let request = new CometChat.MessagesRequestBuilder().setGUID("GUID").setLimit(50).build(); + +// Fetch only unread messages +let request = new CometChat.MessagesRequestBuilder().setUID("UID").setUnread(true).setLimit(30).build(); + +// Fetch only media messages +let request = new CometChat.MessagesRequestBuilder().setUID("UID").setCategories(["message"]).setTypes(["image", "video", "audio", "file"]).setLimit(30).build(); + +// Fetch messages, then paginate +let messages = await request.fetchPrevious(); +``` + The `MessagesRequest` class as you must be familiar with helps you to fetch messages based on the various parameters provided to it. This document will help you understand better the various options that are available using the `MessagesRequest` class. + +**Available via:** [SDK](/sdk/react-native/additional-message-filtering) | [REST API](/rest-api/messages/list-messages) | [UI Kits](/ui-kit/react/message-list#filters) + + The `MessagesRequest` class is designed using the `Builder design pattern`. In order to obtain an object of the `MessagesRequest` class, you will have to make use of the `MessagesRequestBuilder` class in the `MessagesRequest` class. The `MessagesRequestBuilder` class allows you to set various parameters to the `MessagesRequest` class based on which the messages are fetched. @@ -51,6 +76,104 @@ let messagesRequest: CometChat.MessagesRequest = + +**On Success** — `fetchPrevious()` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771397762, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-de89d7ce-f090-4e2e-ad89-bebae957b3ff-1771397690356", + "text": "Nice" + }, + "text": "Nice", + "id": "25234", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771397762, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771398092, + "deliveredAt": 1771398092, + "readAt": 1771404705, + "updatedAt": 1771404705, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages for a user conversation *In other words, how do I fetch messages between me and any user* @@ -58,7 +181,7 @@ let messagesRequest: CometChat.MessagesRequest = This can be achieved using the `setUID()` method. This method takes the UID of the user with whom the conversation is to be fetched. When a valid UID is passed, the SDK will return all the messages that are a part of the conversation between the logged-in user and the UID that has been specified. - + ```javascript let UID = "UID"; let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -80,6 +203,104 @@ let UID: string = "UID", + +**On Success** — `fetchPrevious()` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771397762, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-de89d7ce-f090-4e2e-ad89-bebae957b3ff-1771397690356", + "text": "Nice" + }, + "text": "Nice", + "id": "25234", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771397762, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771398092, + "deliveredAt": 1771398092, + "readAt": 1771404705, + "updatedAt": 1771404705, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages for a group conversation *In other words, how do I fetch messages for any group conversation* @@ -87,7 +308,7 @@ let UID: string = "UID", You can achieve this using the `setGUID()` method. This method takes the GUID of a group for which the conversations are to be fetched. Passing a valid GUID to this method will return all the messages that are a part of the group conversation. Please note that the logged-in user must be a member of the group to fetch the messages for that group. - + ```javascript let GUID = "GUID"; let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -109,12 +330,115 @@ let GUID: string = "GUID", - + +**On Success** — `fetchPrevious()` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1749203133, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 2, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-de89d7ce-f090-4e2e-ad89-bebae957b3ff-1771397690356", + "text": "Nice" + }, + "text": "Nice", + "id": "25237", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1749203133, + "onlineMembersCount": 2, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771400683, + "updatedAt": 1771400683, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + If none of the above two methods `setUID()` and `setGUID()` is used, all the messages for the logged-in user will be fetched. This means that messages from all the one-on-one and group conversations which the logged-in user is a part of will be returned.> All the parameters discussed below can be used along with the setUID() or setGUID() or without any of the two to fetch all the messages that the logged-in user is a part of. - + + ## Messages before/after a message *In other words, how do I fetch messages before or after a particular message* @@ -122,7 +446,7 @@ If none of the above two methods `setUID()` and `setGUID()` is used, all the mes This can be achieved using the `setMessageId()` method. This method takes the message-id as input and provides messages only after/before the message-id based on if the fetchNext() or fetchPrevious() method is triggered. - + ```javascript let UID = "UID"; let messageId = 1; @@ -136,7 +460,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let UID = "UID"; let messageId = 1; @@ -150,7 +474,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", messageId: number = 1, @@ -165,7 +489,7 @@ let UID: string = "UID", - + ```typescript let UID: string = "UID", messageId: number = 1, @@ -182,6 +506,104 @@ let UID: string = "UID", + +**On Success** — `fetchPrevious()` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771397762, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-de89d7ce-f090-4e2e-ad89-bebae957b3ff-1771397690356", + "text": "UnreadHey" + }, + "text": "UnreadHey", + "id": "25233", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771397762, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771398088, + "deliveredAt": 1771398088, + "updatedAt": 1771398088, + "readAt": 1771404705, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific message-id for a particular user/group conversation. ## Messages before/after a given time @@ -191,7 +613,7 @@ This method can be used along with `setUID()` or `setGUID()` methods to fetch me You can easily achieve this using the `setTimestamp()` method. This method takes the Unix timestamp as input and provides messages only after/before the timestamp based on if fetchNext() or fetchPrevious() method is triggered. - + ```javascript let UID = "UID"; let timestamp = 1602221371; @@ -205,7 +627,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let UID = "UID"; let timestamp = 1602221371; @@ -219,7 +641,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID = "UID"; let timestamp = 1602221371; @@ -233,7 +655,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID = "UID"; let timestamp = 1602221371; @@ -249,6 +671,111 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() + +**On Success** — `fetchPrevious()` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "test-custom", + "receiverType": "user", + "category": "custom", + "customData": { + "greeting": "Hello from custom message!", + "timestamp": 1771324022864 + }, + "data": { + "customData": { + "greeting": "Hello from custom message!", + "timestamp": 1771324022864 + }, + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771323089, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771323567, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-5cebfc4b-80f7-44df-8a0a-5a760ffe5239-1771321973734", + "text": "Sent a custom message" + }, + "id": "25191", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771323567, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323089, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771324025, + "deliveredAt": 1771328175, + "readAt": 1771328175, + "updatedAt": 1771328175, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + This method can be used along with `setUID()` or `setGUID()` methods to fetch messages after/before any specific date or time for a particular user/group conversation. ## Unread messages @@ -258,7 +785,7 @@ This method can be used along with `setUID()` or `setGUID()` methods to fetch me This can easily be achieved using setting the unread flag to true. For this, you need to use the `setUnread()` method. This method takes a boolean value as input. If the value is set to true, the SDK will return just the unread messages. - + ```javascript let UID = "UID"; let limit = 30; @@ -271,7 +798,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let UID = "UID"; let limit = 30; @@ -284,20 +811,21 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); +let UID: string = "UID"; +let limit: number = 30; +let messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setUnread(true) + .setLimit(limit) + .build(); ``` - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -313,6 +841,103 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771413280, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771413285, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-3f872f7b-f581-40da-b6d3-96ebb6de9cdf-1771411970682", + "text": "You there?" + }, + "text": "You there?", + "id": "25241", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771413285, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771413280, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771413707, + "deliveredAt": 1771413707, + "updatedAt": 1771413707, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + This method along with `setGUID()` or `setUID()` can be used to fetch unread messages for a particular group or user conversation respectively. ## Exclude messages from blocked users @@ -322,7 +947,7 @@ This method along with `setGUID()` or `setUID()` can be used to fetch unread mes This can be easily achieved using the `hideMessagesFromBlockedUsers()` method. This method accepts a boolean value which determines if the messages from users blocked by the logged-in user need to be a part if the fetched messages. If the value is set to true, the messages will be hidden and won't be a part of the messages fetched. The default value is false i.e if this method is not used, the messages from blocked users will be included in the fetched messages. - + ```javascript let UID = "UID"; let limit = 30; @@ -335,7 +960,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -348,7 +973,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -362,7 +987,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -378,6 +1003,121 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (messages from blocked users are excluded): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "group-call", + "receiverType": "group", + "category": "custom", + "customData": { + "callType": "audio", + "isCaller": true, + "sessionId": "v1.in.2748663902141719.1771413265424256434f95643946315f45d0fd9058f55b625b" + }, + "data": { + "customData": { + "callType": "audio", + "isCaller": true, + "sessionId": "v1.in.2748663902141719.1771413265424256434f95643946315f45d0fd9058f55b625b" + }, + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1748437105, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771412068, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-8de3c0b7-fa09-4b9e-b321-9a085d81b1d5-1771411979132", + "text": "Group video call started. Tap to join!" + }, + "id": "25239", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771412068, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1748437105, + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771413265, + "updatedAt": 1771413265, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + This method can be used to hide the messages by users blocked by logged in user in groups that both the members are a part of. ## Updated and received messages @@ -387,7 +1127,7 @@ This method can be used to hide the messages by users blocked by logged in user This method accepts a Unix timestamp value and will return all the messages that have been updated and the ones that have been sent/received after the specified time. The messages updated could mean the messages that have been marked as read/delivered or if the messages are edited or deleted. - + ```javascript let UID = "UID"; let limit = 30; @@ -401,7 +1141,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let UID = "UID"; let limit = 30; @@ -415,7 +1155,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID = "UID"; let limit = 30; @@ -429,7 +1169,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -446,16 +1186,114 @@ let GUID: string = "GUID", + +**On Success** — `fetchNext()` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771397762, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-de89d7ce-f090-4e2e-ad89-bebae957b3ff-1771397690356", + "text": "Nice" + }, + "text": "Nice", + "id": "25234", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771397762, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771398092, + "deliveredAt": 1771398092, + "readAt": 1771404705, + "updatedAt": 1771404705, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + This can be useful in finding the messages that have been received or updated after a certain time. Can prove very useful if you are saving the messages locally and would like to know the messages that have been updated or received after the last message available in your local databases. ## Updated messages only *In other words, how do I fetch messages that have been updated after a particular date or time* -This can be achieved easily by setting the updatesOnly parameter to true. To do so, you can use the updatesOnly() method. This method takes a boolean input and can be used with the `setUpdatedAfter()` method to get jus the updated messages and not the messages sent/received after the specified time. This method cannot be used independently and always needs to be used with the `setUpdatedAfter()` method. +This can be achieved easily by setting the updatesOnly parameter to true. To do so, you can use the updatesOnly() method. This method takes a boolean input and can be used with the `setUpdatedAfter()` method to get just the updated messages and not the messages sent/received after the specified time. This method cannot be used independently and always needs to be used with the `setUpdatedAfter()` method. - + ```javascript let UID = "UID"; let limit = 30; @@ -470,7 +1308,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -485,7 +1323,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -501,7 +1339,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -519,6 +1357,99 @@ let GUID: string = "GUID", + +**On Success** — `fetchNext()` returns (only updated messages, e.g. read receipt changes): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "png", + "mimeType": "image/png", + "name": "photo.png", + "size": 2295572, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771323061_1750099251_c35f9734fc20947b7456bbea68126f99.png" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771322968, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323060, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-542c56fc-a1a6-4df4-a5e4-549f3cf17550-1771321970718", + "type": "image", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771323061_1750099251_c35f9734fc20947b7456bbea68126f99.png" + }, + "id": "25189", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323060, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771322968, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771323061, + "deliveredAt": 1771323062, + "readAt": 1771323227, + "updatedAt": 1771323227 + }, + // ... more messages up to the specified limit +] +``` + + ## Messages for multiple categories *In other words, how do I fetch messages belonging to multiple categories* @@ -528,7 +1459,7 @@ We recommend before trying this, you refer to the [Message structure and hierarc For this, you will have to use the `setCategories()` method. This method accepts a list of categories. This tells the SDK to fetch messages only belonging to these categories. - + ```javascript let UID = "UID"; let limit = 30; @@ -542,7 +1473,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -556,7 +1487,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -571,7 +1502,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -588,6 +1519,256 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (includes both `custom` and `message` categories): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "extension_poll", + "receiverType": "user", + "category": "custom", + "customData": { + "id": "fde49a5e-baa8-4e04-95e9-c2c09557caa0", + "options": { + "1": "Yes", + "2": "No" + }, + "question": "Custom" + }, + "data": { + "customData": { + "id": "fde49a5e-baa8-4e04-95e9-c2c09557caa0", + "options": { + "1": "Yes", + "2": "No" + }, + "question": "Custom" + }, + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "createdAt": 1746375164, + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "createdAt": 1746375164, + "lastActiveAt": 1771474104, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + }, + "polls": { + "id": "fde49a5e-baa8-4e04-95e9-c2c09557caa0", + "options": { + "1": "Yes", + "2": "No" + }, + "question": "Custom", + "results": { + "options": { + "1": { + "count": 0, + "text": "Yes" + }, + "2": { + "count": 0, + "text": "No" + } + }, + "total": 0 + } + } + } + }, + "incrementUnreadCount": true, + "pushNotification": "Poll: Custom" + }, + "text": "Custom", + "updateConversation": true + }, + "id": "25251", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474104, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474256, + "deliveredAt": 1771474256, + "readAt": 1771474256, + "updatedAt": 1771474256, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + }, + "polls": { + "id": "fde49a5e-baa8-4e04-95e9-c2c09557caa0", + "options": { + "1": "Yes", + "2": "No" + }, + "question": "Custom", + "results": { + "options": { + "1": { + "count": 0, + "text": "Yes" + }, + "2": { + "count": 0, + "text": "No" + } + }, + "total": 0 + } + } + } + }, + "incrementUnreadCount": true, + "pushNotification": "Poll: Custom" + } + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474104, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "Hello Message" + }, + "text": "Hello Message", + "id": "25252", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474104, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474273, + "deliveredAt": 1771474274, + "readAt": 1771474274, + "updatedAt": 1771474274, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + The above snippet will help you get only the messages belonging to the `message` and `custom` category. This can also be used to disable certain categories of messages like `call` and `action`. This along with `setGUID()` and `setUID()` can help display only the messages you wish to display avoiding the other category of messages. ## Messages for multiple types @@ -599,7 +1780,7 @@ We recommend before trying this, you refer to the [Message structure and hierarc This can be easily achieved using the `setTypes()` method. This method accepts a list of types. This tells the SDK to fetch messages only belonging to these types. - + ```javascript let UID = "UID"; let limit = 30; @@ -615,7 +1796,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -631,7 +1812,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let GUID = "GUID"; let limit = 30; @@ -647,7 +1828,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -666,19 +1847,190 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (only `image`, `video`, `audio`, `file` types): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "jpg", + "mimeType": "image/jpeg", + "name": "photo.jpg", + "size": 142099, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474540_739339167_565af45463f0170fda1720c8138a7761.jpg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474535, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "type": "image", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474540_739339167_565af45463f0170fda1720c8138a7761.jpg" + }, + "id": "25253", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474535, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474540, + "deliveredAt": 1771474540, + "readAt": 1771474540, + "updatedAt": 1771474540 + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "audio", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "ogg", + "mimeType": "application/ogg", + "name": "audio.ogg", + "size": 12059, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474570_2022717407_2842560f3be961ab9264c48b5721a60d.ogg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474559, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "type": "audio", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474570_2022717407_2842560f3be961ab9264c48b5721a60d.ogg" + }, + "id": "25254", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474559, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474570, + "deliveredAt": 1771474570, + "readAt": 1771474570, + "updatedAt": 1771474570 + }, + // ... more messages up to the specified limit +] +``` + + Using the above code snippet, you can fetch all the media messages. This along with setUID() or setGUID() can be used to fetch media messages for any particular conversation. This can be useful in many other scenarios as well. ## Messages for a specific thread -*\*In other words, how do I fetch messages that are a part of a thread and not directly a user/group conversations* +*In other words, how do I fetch messages that are a part of a thread and not directly a user/group conversation* This can be done using the `setParentMessageId()` method. This method needs to be used when you have implemented threaded conversations in your app. This method will return the messages only belonging to the thread with the specified parent Id. - + ```javascript let UID = "UID"; -let messageId = 1; +let messageId = 1; // Use msg.getId() on a message where msg.getReplyCount() > 0 let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) @@ -689,10 +2041,10 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; -let messageId = 1; +let messageId = 1; // Use msg.getId() on a message where msg.getReplyCount() > 0 let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) @@ -703,11 +2055,11 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, - messageId: number = 1, + messageId: number = 1, // Use msg.getId() on a message where msg.getReplyCount() > 0 messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) @@ -718,11 +2070,11 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, - messageId: number = 1, + messageId: number = 1, // Use msg.getId() on a message where msg.getReplyCount() > 0 messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) @@ -735,8 +2087,108 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (messages belonging to the specified thread): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771475047, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "Thread Message" + }, + "text": "Thread Message", + "id": "25257", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771475047, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771476403, + "deliveredAt": 1771476404, + "readAt": 1771476404, + "updatedAt": 1771476404, + "parentMessageId": "25256", + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + The above code snippet returns the messages that belong to the thread with parent id 100. + ## Hide threaded messages in user/group conversations *In other words, how do I exclude threaded messages from the normal user/group conversations* @@ -744,7 +2196,7 @@ The above code snippet returns the messages that belong to the thread with paren In order to do this, you can use the `hideReplies()` method. This method is also related to threaded conversations. This method takes boolean as input. This boolean when set to true will make sure that the messages that belong to threads are not fetched. If set to false, which is also the default value, the messages belong to the threads will also be fetched along with other messages. - + ```javascript let UID = "UID"; let limit = 30; @@ -757,7 +2209,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -770,7 +2222,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -784,7 +2236,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -800,14 +2252,194 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (threaded replies are excluded, parent messages with threads still appear): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "audio", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "ogg", + "mimeType": "application/ogg", + "name": "audio.ogg", + "size": 12059, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474570_2022717407_2842560f3be961ab9264c48b5721a60d.ogg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474559, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "type": "audio", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474570_2022717407_2842560f3be961ab9264c48b5721a60d.ogg" + }, + "id": "25254", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474559, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474570, + "deliveredAt": 1771474570, + "readAt": 1771474570, + "updatedAt": 1771474570 + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771475047, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "New Message for Thread" + }, + "text": "New Message for Thread", + "id": "25256", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771475047, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771476391, + "deliveredAt": 1771476392, + "readAt": 1771476392, + "updatedAt": 1771476392, + "replyCount": 1, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Hide deleted messages in user/group conversations -*In other words, how do I exclude deleted messages from a user/group conversations* +*In other words, how do I exclude deleted messages from a user/group conversation* In order to do this, you can use the `hideDeletedMessages()` method. This method takes boolean as input. This boolean when set to true will make sure that the deleted messages are not fetched. If set to false, which is also the default value, the deleted messages will also be fetched along with other messages. - + ```javascript let UID = "UID"; let limit = 30; @@ -820,7 +2452,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -833,7 +2465,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -847,7 +2479,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -863,6 +2495,195 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (deleted messages are excluded): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771475047, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "New Message for Thread" + }, + "text": "New Message for Thread", + "id": "25256", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771475047, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771476391, + "deliveredAt": 1771476392, + "readAt": 1771476392, + "updatedAt": 1771476392, + "replyCount": 1, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771475047, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "Thread Message" + }, + "text": "Thread Message", + "id": "25257", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771475038, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771475047, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771476403, + "deliveredAt": 1771476404, + "readAt": 1771476404, + "updatedAt": 1771476404, + "parentMessageId": "25256", + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages by tags *In other words, how do I fetch messages by tags* @@ -870,7 +2691,7 @@ let GUID: string = "GUID", In order to do this, you can use the `setTags()` method. This method accepts a list of tags. This tells the SDK to fetch messages only belonging to these tags. - + ```javascript let UID = "UID"; let limit = 30; @@ -884,7 +2705,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -898,7 +2719,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -913,7 +2734,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -930,6 +2751,194 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (only messages matching the specified tags): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771477541, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771478591, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "Tagged message for docs" + }, + "text": "Tagged message for docs", + "id": "25259", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771478591, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771477541, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771478898, + "deliveredAt": 1771478900, + "readAt": 1771478900, + "updatedAt": 1771478900, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771478591, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771477541, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-99626bfc-ffc1-4059-be3a-b7c77ee4cbcd-1771474097650", + "text": "Tagged message for docs" + }, + "text": "Tagged message for docs", + "id": "25260", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771477541, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771478591, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771478922, + "updatedAt": 1771478922, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages with tags *In other words, how do I fetch messages with the tags information* @@ -937,7 +2946,7 @@ let GUID: string = "GUID", In order to do this, you can use the `withTags()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages along with the tags. When set to `false` , the SDK will not fetch tags associated with messages. The default value for this parameter is `false` . - + ```javascript let UID = "UID"; let limit = 30; @@ -950,7 +2959,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -963,7 +2972,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -977,7 +2986,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -993,9 +3002,200 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (messages include the `tags` field): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771480251, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771480243, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-99626bfc-ffc1-4059-be3a-b7c77ee4cbcd-1771474097650", + "text": "Tagged message for docs" + }, + "text": "Tagged message for docs", + "id": "25265", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771480243, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771480251, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771481257, + "updatedAt": 1771481257, + "tags": ["starredMessage"], + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771480251, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771480243, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "pending" + }, + "resource": "REACT_NATIVE-4_0_14-99626bfc-ffc1-4059-be3a-b7c77ee4cbcd-1771474097650", + "text": "Tagged message for docs" + }, + "text": "Tagged message for docs", + "id": "25266", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771480243, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771480251, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771481270, + "updatedAt": 1771481270, + "tags": ["starredMessage"], + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages with links -In other words, as a logged-in user, how do I fetch messages that contains links? +*In other words, as a logged-in user, how do I fetch messages that contain links?* In order to do this, you can use the `hasLinks()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have links in the text. The default value for this parameter is `false`. @@ -1006,7 +3206,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1019,7 +3219,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1062,9 +3262,228 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (only messages containing links): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771480243, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771480251, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [ + { + "description": "Build real time chat, voice and video calling experience with CometChat's flexible SDKs, APIs & UI Kits. Sign up now!\n", + "favicon": "https://cometchat.com/_static/favicon.png", + "image": "https://a.storyblok.com/f/231922/1200x630/d639d0748b/open-graph-image.png/m/1200x630/", + "title": "In-app Chat SDK & API For Messaging And Calling - CometChat", + "url": "https://cometchat.com" + } + ] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "Please checkout our website https://cometchat.com" + }, + "text": "Please checkout our website https://cometchat.com", + "id": "25269", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771480251, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771480243, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771481824, + "deliveredAt": 1771481825, + "readAt": 1771481825, + "updatedAt": 1771481825, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [ + { + "description": "Build real time chat, voice and video calling experience with CometChat's flexible SDKs, APIs & UI Kits. Sign up now!\n", + "favicon": "https://cometchat.com/_static/favicon.png", + "image": "https://a.storyblok.com/f/231922/1200x630/d639d0748b/open-graph-image.png/m/1200x630/", + "title": "In-app Chat SDK & API For Messaging And Calling - CometChat", + "url": "https://cometchat.com" + } + ] + } + } + } + } + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771482544, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771482552, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [ + { + "description": "", + "favicon": "http://www.google.com/favicon.ico", + "image": "", + "title": "Google", + "url": "http://www.google.com" + } + ] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "Www.google.com" + }, + "text": "Www.google.com", + "id": "25270", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771482552, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771482544, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771482630, + "deliveredAt": 1771482631, + "readAt": 1771482631, + "updatedAt": 1771482631, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [ + { + "description": "", + "favicon": "http://www.google.com/favicon.ico", + "image": "", + "title": "Google", + "url": "http://www.google.com" + } + ] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages with attachments -In other words, as a logged-in user, how do I fetch messages that contains attachments? +*In other words, as a logged-in user, how do I fetch messages that contain attachments?* In order to do this, you can use the `hasAttachments()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have attachments (image, audio, video or file). The default value for this parameter is `false`. @@ -1075,7 +3494,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1088,7 +3507,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1131,9 +3550,180 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (only messages with attachments): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "jpg", + "mimeType": "image/jpeg", + "name": "IMG_20260217_150412.jpg", + "size": 142099, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474540_739339167_565af45463f0170fda1720c8138a7761.jpg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474535, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "type": "image", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474540_739339167_565af45463f0170fda1720c8138a7761.jpg" + }, + "id": "25253", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474535, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474540, + "deliveredAt": 1771474540, + "readAt": 1771474540, + "updatedAt": 1771474540 + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "audio", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "ogg", + "mimeType": "application/ogg", + "name": "Music%20Box.ogg", + "size": 12059, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474570_2022717407_2842560f3be961ab9264c48b5721a60d.ogg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474559, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "type": "audio", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474570_2022717407_2842560f3be961ab9264c48b5721a60d.ogg" + }, + "id": "25254", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474559, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474570, + "deliveredAt": 1771474570, + "readAt": 1771474570, + "updatedAt": 1771474570 + }, + // ... more messages up to the specified limit +] +``` + + ## Messages with reactions -In other words, as a logged-in user, how do I fetch messages that contains reactions? +*In other words, as a logged-in user, how do I fetch messages that contain reactions?* In order to do this, you can use the `hasReactions()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have reactions. The default value for this parameter is `false`. @@ -1144,7 +3734,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1157,7 +3747,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1200,9 +3790,118 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (only messages that have reactions): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771494233, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Message with reactions", + "reactions": [ + { + "reaction": "❤️", + "count": 1 + }, + { + "reaction": "😮", + "count": 1, + "reactedByMe": true + } + ] + }, + "text": "Message with reactions", + "id": "25275", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771495045, + "deliveredAt": 1771495045, + "readAt": 1771495045, + "updatedAt": 1771495045, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages with mentions -In other words, as a logged-in user, how do I fetch messages that contains mentions? +*In other words, as a logged-in user, how do I fetch messages that contain mentions?* In order to do this, you can use the `hasMentions()` method. This method accepts boolean as input. When set to `true` , the SDK will fetch messages which have mentions. The default value for this parameter is `false`. @@ -1213,7 +3912,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1226,7 +3925,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1269,9 +3968,240 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (only messages that contain mentions): +```json +[ + { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771482544, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771482552, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "<@uid:cometchat-uid-2> Hello", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771494233 + } + } + }, + "text": "<@uid:cometchat-uid-2> Hello", + "id": "25271", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771482552, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771482544, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771482742, + "deliveredAt": 1771482743, + "readAt": 1771482743, + "updatedAt": 1771482743, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771494233, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771494233 + } + } + }, + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "id": "25276", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771495242, + "deliveredAt": 1771495244, + "readAt": 1771495244, + "updatedAt": 1771495244, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages with particular user mentions -In other words, as a logged-in user, how do I fetch messages that mentions specific users? +*In other words, as a logged-in user, how do I fetch messages that mention specific users?* In order to do this, you can use the `setMentionedUIDs()` method. This method accepts an array of UIDs as input. When set, the SDK will fetch messages which have the mentions of the UIDs passed. @@ -1282,7 +4212,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1295,7 +4225,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1338,9 +4268,240 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns (only messages mentioning the specified UIDs): +```json +[ + { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771482544, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771482552, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "text": "<@uid:cometchat-uid-2> Hello", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771494233 + } + } + }, + "text": "<@uid:cometchat-uid-2> Hello", + "id": "25271", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771482552, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771482544, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771482742, + "deliveredAt": 1771482743, + "readAt": 1771482743, + "updatedAt": 1771482743, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771494233, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771494233 + } + } + }, + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "id": "25276", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771495242, + "deliveredAt": 1771495244, + "readAt": 1771495244, + "updatedAt": 1771495244, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit +] +``` + + ## Messages with specific attachment types -In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments? +*In other words, as a logged-in user, how do I fetch messages that contain specific types of attachments?* In order to do this, you can use the `setAttachmentTypes()` method. This method accepts an array of `CometChat.AttachmentType` ENUM values as input. When provided, the SDK will fetch only those messages that include attachments of the specified types (such as image, audio, video, or file). @@ -1351,7 +4512,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1364,7 +4525,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1406,3 +4567,221 @@ let GUID: string = "GUID", + + +**On Success** — `fetchPrevious()` returns (only messages with the specified attachment types): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "jpg", + "mimeType": "image/jpeg", + "name": "IMG_20260217_150412.jpg", + "size": 142099, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771386517_1811543964_565af45463f0170fda1720c8138a7761.jpg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771386436, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386507, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "resource": "REACT_NATIVE-4_0_14-e00a3397-8084-4596-9425-35f7e61a1111-1771332420737", + "type": "image", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771386517_1811543964_565af45463f0170fda1720c8138a7761.jpg" + }, + "id": "25196", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386507, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771386436, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771386517, + "deliveredAt": 1771386517, + "readAt": 1771483750, + "updatedAt": 1771483750 + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "jpg", + "mimeType": "image/jpeg", + "name": "IMG_20260217_150412.jpg", + "size": 142099, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474540_739339167_565af45463f0170fda1720c8138a7761.jpg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771474191, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474535, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "resource": "REACT_NATIVE-4_0_14-d4a0f137-38d3-46d2-85e7-01084854e826-1771474101564", + "type": "image", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771474540_739339167_565af45463f0170fda1720c8138a7761.jpg" + }, + "id": "25253", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771474535, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771474191, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771474540, + "deliveredAt": 1771474540, + "readAt": 1771474540, + "updatedAt": 1771474540 + }, + // ... more messages up to the specified limit +] +``` + + +## Best Practices & Troubleshooting + + + + Always call `fetchNext()` or `fetchPrevious()` on the same `MessagesRequest` object to paginate through results. Creating a new `MessagesRequest` object will reset pagination and start from the beginning. + + + + You can chain multiple builder methods together (e.g., `setCategories()` + `setTypes()` + `setUID()`) to narrow down results. This is more efficient than fetching all messages and filtering client-side. + + + + If you store messages locally, use `setUpdatedAfter()` with the timestamp of your last synced message to fetch only new or updated messages. Combine with `updatesOnly(true)` if you only need edits, deletions, and read/delivery status changes. + + + + The maximum limit per fetch is `100`. For most UI use cases, a limit of `30–50` provides a good balance between performance and user experience. Smaller limits mean faster responses and less memory usage. + + + + If `fetchNext()` or `fetchPrevious()` returns an empty array, verify that: the logged-in user is a member of the group (for group conversations), the UID/GUID is correct, and the applied filters aren't too restrictive. Try removing filters one at a time to isolate the issue. + + + + Methods like `hasLinks()`, `hasAttachments()`, `hasReactions()`, `hasMentions()`, `setMentionedUIDs()`, and `setAttachmentTypes()` require the Conversation & Advanced Search feature to be enabled. Ensure you are on an Advanced or Custom [plan](https://www.cometchat.com/pricing) and have enabled the feature from the [CometChat Dashboard](https://app.cometchat.com) (Chats → Settings → General Configuration). + + + +--- + +## Next Steps + + + + Listen for and handle incoming real-time messages + + + Send text, media, and custom messages to users and groups + + + Understand message categories, types, and structure + + + Fetch and display conversation lists with latest messages + + diff --git a/sdk/react-native/advanced-overview.mdx b/sdk/react-native/advanced-overview.mdx index 7a8e791f6..4005cee48 100644 --- a/sdk/react-native/advanced-overview.mdx +++ b/sdk/react-native/advanced-overview.mdx @@ -1,8 +1,18 @@ --- title: "Advanced" sidebarTitle: "Overview" +description: "Advanced CometChat React Native SDK topics including connection status monitoring and manual WebSocket management." --- +This section helps you to know about the Connection Listeners. +## Next Steps -This section helps you to know about the Connection Listeners. + + +Monitor real-time WebSocket connection status + + +Take control of WebSocket connections + + diff --git a/sdk/react-native/ai-agents.mdx b/sdk/react-native/ai-agents.mdx index f4b88d96a..f6d1464ad 100644 --- a/sdk/react-native/ai-agents.mdx +++ b/sdk/react-native/ai-agents.mdx @@ -1,17 +1,36 @@ --- title: "AI Agents" +description: "Learn how to integrate AI Agents in your React Native app using the CometChat SDK, including real-time event streaming and agentic message handling." --- -# AI Agents Overview + +**Quick Reference** +```javascript +// Listen for real-time AI Agent events +CometChat.addAIAssistantListener("listenerId", { + onAIAssistantEventReceived: (event) => {} +}); + +// Listen for persisted agentic messages +CometChat.addMessageListener("listenerId", { + onAIAssistantMessageReceived: (message) => {}, + onAIToolResultReceived: (message) => {}, + onAIToolArgumentsReceived: (message) => {} +}); +``` + + +## Overview AI Agents enable intelligent, automated interactions within your application. They can process user messages, trigger tools, and respond with contextually relevant information. For a broader introduction, see the [AI Agents section](/ai-agents). -> **Note:** -> Currently, an Agent only responds to **Text Messages**. + +Currently, an Agent only responds to **Text Messages**. + ## Agent Run Lifecycle and Message Flow -This section explains how a user’s text message to an Agent becomes a structured "run" which emits real-time events and then produces agentic messages for historical retrieval. +This section explains how a user's text message to an Agent becomes a structured "run" which emits real-time events and then produces agentic messages for historical retrieval. - A user sends a text message to an Agent. - The platform starts a run and streams real-time events via the **`AIAssistantListener`**. - After the run completes, persisted Agentic Messages arrive via the **`MessageListener`**. @@ -34,7 +53,7 @@ Events are received via the **`onAIAssistantEventReceived`** method of the **`AI Notes: - `Run Start` and `Run Finished` are always emitted. - `Tool Call` events appear only when a backend or frontend tool is invoked. There can be multiple tool calls in a single run. -- `Text Message` events are always emitted and carry the assistant’s reply incrementally. +- `Text Message` events are always emitted and carry the assistant's reply incrementally. @@ -69,16 +88,26 @@ Notes: -#### Event descriptions -- Run Start: A new run has begun for the user’s message. -- Tool Call Start: The agent decided to invoke a tool. -- Tool Call Arguments: Arguments being passed to the tool. -- Tool Call End: Tool execution completed. -- Tool Call Result: Tool’s output is available. -- Text Message Start: The agent started composing a reply. -- Text Message Content: Streaming content chunks for progressive rendering. -- Text Message End: The agent reply is complete. -- Run Finished: The run is finalized; persisted messages will follow. + +Always remove AI Assistant listeners when the component unmounts to prevent memory leaks. +```javascript +CometChat.removeAIAssistantListener("unique_listener_id"); +``` + + +#### Event Descriptions + +| Event | Description | +|-------|-------------| +| Run Start | A new run has begun for the user's message | +| Tool Call Start | The agent decided to invoke a tool | +| Tool Call Arguments | Arguments being passed to the tool | +| Tool Call End | Tool execution completed | +| Tool Call Result | Tool's output is available | +| Text Message Start | The agent started composing a reply | +| Text Message Content | Streaming content chunks for progressive rendering | +| Text Message End | The agent reply is complete | +| Run Finished | The run is finalized; persisted messages will follow | ### Agentic Messages @@ -131,4 +160,39 @@ These events are received via the **`MessageListener`** after the run completes. CometChat.removeMessageListener(listnerId); ``` - \ No newline at end of file + + + +Always remove message listeners when the component unmounts to prevent memory leaks. +```javascript +CometChat.removeMessageListener("unique_listener_id"); +``` + + + + +- Register both `AIAssistantListener` (for real-time streaming) and `MessageListener` (for persisted messages) to get the complete agent interaction flow +- Use `Text Message Content` events for progressive rendering of the agent's reply as it streams in +- Handle `Tool Call` events to show tool execution status in your UI (e.g., loading indicators) +- Always remove both listeners on component unmount to avoid memory leaks +- Since agents only respond to text messages, validate the message type before sending to an agent + + + +- **No events received**: Ensure you registered the `AIAssistantListener` with a unique listener ID before sending a message to the agent. +- **Missing agentic messages**: Agentic messages arrive via `MessageListener` after the run completes. Make sure you have both listeners registered. +- **Duplicate events**: Verify you are not registering the same listener ID multiple times without removing the previous one. +- **Tool call events not appearing**: Tool call events only fire when the agent invokes a tool. Not all runs include tool calls. + + + +## Next Steps + + + +Explore the full AI Agents platform documentation + + +Automatically moderate messages using AI + + diff --git a/sdk/react-native/ai-moderation.mdx b/sdk/react-native/ai-moderation.mdx index 148cbd0ad..fcaa57fd8 100644 --- a/sdk/react-native/ai-moderation.mdx +++ b/sdk/react-native/ai-moderation.mdx @@ -1,7 +1,26 @@ --- title: "AI Moderation" +description: "Learn how to use AI-powered message moderation in your React Native app using the CometChat SDK, including real-time moderation events and handling disapproved messages." --- + +**Quick Reference** +```javascript +// Send a message and check moderation status +CometChat.sendMessage(textMessage).then((message) => { + const status = message.getModerationStatus(); + // CometChat.ModerationStatus.PENDING | APPROVED | DISAPPROVED +}); + +// Listen for moderation results +CometChat.addMessageListener("listenerId", new CometChat.MessageListener({ + onMessageModerated: (message) => { + const status = message.getModerationStatus(); + } +})); +``` + + ## Overview AI Moderation in the CometChat SDK helps ensure that your chat application remains safe and compliant by automatically reviewing messages for inappropriate content. This feature leverages AI to moderate messages in real-time, reducing manual intervention and improving user experience. @@ -16,7 +35,7 @@ Before using AI Moderation, ensure the following: 1. Moderation is enabled for your app in the [CometChat Dashboard](https://app.cometchat.com) 2. Moderation rules are configured under **Moderation > Rules** -3. You're using CometChat SDK version that supports moderation +3. You're using a CometChat SDK version that supports moderation ## How It Works @@ -202,6 +221,13 @@ Register a message listener to receive moderation results in real-time: + +Always remove message listeners when the component unmounts to prevent memory leaks. +```javascript +CometChat.removeMessageListener("MODERATION_LISTENER"); +``` + + ### Step 3: Handle Disapproved Messages When a message is disapproved, handle it appropriately in your UI: @@ -223,5 +249,30 @@ function handleDisapprovedMessage(message) { } ``` + + +- Always check `getModerationStatus()` after sending a message to show appropriate UI indicators (e.g., a pending badge) +- Register the `onMessageModerated` listener early in your app lifecycle so you don't miss moderation results +- Provide clear feedback to users when their message is disapproved — avoid silently hiding content without explanation +- Custom and Action messages are not moderated — if you need moderation on custom message types, implement your own server-side checks +- Consider caching moderation status locally to avoid re-checking on message list re-renders + + + +- **Moderation status always PENDING**: Ensure moderation rules are configured in the CometChat Dashboard under **Moderation > Rules**. +- **`onMessageModerated` not firing**: Verify you registered a `MessageListener` with the correct listener ID and that moderation is enabled for your app. +- **Custom messages not being moderated**: This is expected — AI Moderation only applies to text, image, and video messages. +- **Disapproved messages still visible**: Make sure your `onMessageModerated` handler updates the UI when a message status changes to `DISAPPROVED`. + + + ## Next Steps -After implementing AI Moderation, consider adding a reporting feature to allow users to flag messages they find inappropriate. For more details, see the [Flag Message](/sdk/react-native/flag-message) documentation. \ No newline at end of file + + + +Allow users to report inappropriate messages + + +Add intelligent AI agent interactions + + diff --git a/sdk/react-native/authentication-overview.mdx b/sdk/react-native/authentication-overview.mdx index 73ef4f107..c37a01650 100644 --- a/sdk/react-native/authentication-overview.mdx +++ b/sdk/react-native/authentication-overview.mdx @@ -1,9 +1,23 @@ --- title: "Authentication" sidebarTitle: "Overview" +description: "Learn how to create users, log in with Auth Key or Auth Token, and manage user sessions in CometChat React Native SDK." --- + +**Quick Reference** - Login with Auth Key (dev) or Auth Token (production): +```javascript +// Auth Key login (development only) +const user = await CometChat.login("USER_UID", "AUTH_KEY"); + +// Auth Token login (recommended for production) +const user = await CometChat.login("AUTH_TOKEN"); + +// Check existing session +const loggedInUser = await CometChat.getLoggedinUser(); +``` + ## Create User @@ -13,10 +27,7 @@ Before you log in a user, you must add the user to CometChat. 2. **For production apps**: Use the CometChat [Create User API](https://api-explorer.cometchat.com/reference/creates-user) to create the user when your user signs up in your app. -Sample Users - -We have setup 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`. - +**Sample Users:** We have set up 5 users for testing with UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`. Once initialization is successful, you will need to log the user into CometChat using the `login()` method. @@ -24,136 +35,169 @@ Once initialization is successful, you will need to log the user into CometChat We recommend you call the CometChat login method once your user logs into your app. The `login()` method needs to be called only once. - -The CometChat SDK maintains the session of the logged-in user within the SDK. Thus you do not need to call the login method for every session. You can use the CometChat.getLoggedinUser() method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns null, it implies there is no session present within the SDK and you need to log the user into ComeChat. - +The CometChat SDK maintains the session of the logged-in user within the SDK. Thus you do not need to call the login method for every session. You can use the `CometChat.getLoggedinUser()` method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. If this method returns `null`, it implies there is no session present within the SDK and you need to log the user into CometChat. ## Login using Auth Key -This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [AuthToken](#login-using-auth-token) instead of an Auth Key to ensure enhanced security. + +**Security Warning:** This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, we strongly recommend using an [Auth Token](#login-using-auth-token) instead of an Auth Key to ensure enhanced security. + - -```javascript -var UID = "UID"; -var authKey = "AUTH_KEY"; - -CometChat.getLoggedinUser().then( - (user) => { - if (!user) { - CometChat.login(UID, authKey).then( - (user) => { - console.log("Login Successful:", { user }); - }, - (error) => { - console.log("Login failed with exception:", { error }); + + ```javascript + var UID = "UID"; + var authKey = "AUTH_KEY"; + + // Check if user is already logged in before calling login + CometChat.getLoggedinUser().then( + (user) => { + if (!user) { + CometChat.login(UID, authKey).then( + (user) => { + console.log("Login Successful:", user); + }, + (error) => { + console.log("Login failed with exception:", error); + } + ); } - ); - } - }, - (error) => { - console.log("Something went wrong", error); - } -); -``` - - - - -```javascript -var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; - -CometChat.getLoggedinUser().then( - (user: CometChat.User) => { - if (!user) { - CometChat.login(UID, authKey).then( - (user: CometChat.User) => { - console.log("Login Successful:", { user }); - }, - (error: CometChat.CometChatException) => { - console.log("Login failed with exception:", { error }); + }, + (error) => { + console.log("Something went wrong", error); + } + ); + ``` + + + ```typescript + var UID: string = "cometchat-uid-1", + authKey: string = "AUTH_KEY"; + + // Check if user is already logged in before calling login + CometChat.getLoggedinUser().then( + (user: CometChat.User) => { + if (!user) { + CometChat.login(UID, authKey).then( + (user: CometChat.User) => { + console.log("Login Successful:", user); + }, + (error: CometChat.CometChatException) => { + console.log("Login failed with exception:", error); + } + ); } - ); - } - }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); - } -); -``` - - - + }, + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", error); + } + ); + ``` + -| Parameters | Description | -| ---------- | ------------------------------------------------ | -| UID | The UID of the user that you would like to login | -| authKey | CometChat Auth Key | +| Parameter | Description | +| --------- | ------------------------------------------------ | +| UID | The UID of the user that you would like to login | +| authKey | CometChat Auth Key | After the user logs in, their information is returned in the `User` object on `Promise` resolved. + +**On Success** — `console.log("Login Successful:", user)` returns: +```json +Login Successful: { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "authToken": "cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771311515, + "role": "default", + "status": "online", + "tags": [] +} +``` + +**On Failure** — `console.log("Login failed with exception:", error)` returns: +```json +Login failed with exception: { + "code": "ERR_UID_NOT_FOUND", + "name": "UID not found", + "message": "The UID provided does not exist.", + "details": {} +} +``` + + ## Login using Auth Token -This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety. +This advanced authentication procedure does not use the Auth Key directly in your client code, thus ensuring safety. -1. [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. -2. [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database. -3. Load the Auth Token in your client and pass it to the `login()` method. + + + [Create a User](https://api-explorer.cometchat.com/reference/creates-user) via the CometChat API when the user signs up in your app. + + + [Create an Auth Token](https://api-explorer.cometchat.com/reference/create-authtoken) via the CometChat API for the new user and save the token in your database. + + + Load the Auth Token in your client and pass it to the `login()` method. + + - -```javascript -var authToken = "AUTH_TOKEN"; - -CometChat.getLoggedinUser().then( - (user) => { - if (!user) { - CometChat.login(authToken).then( - (user) => { - console.log("Login Successful:", { user }); - }, - (error) => { - console.log("Login failed with exception:", { error }); + + ```javascript + var authToken = "AUTH_TOKEN"; + + // Check if user is already logged in before calling login + CometChat.getLoggedinUser().then( + (user) => { + if (!user) { + CometChat.login(authToken).then( + (user) => { + console.log("Login Successful:", user); + }, + (error) => { + console.log("Login failed with exception:", error); + } + ); } - ); - } - }, - (error) => { - console.log("Something went wrong", error); - } -); -``` - - - - -```javascript -var authToken: string = "AUTH_TOKEN"; - -CometChat.getLoggedinUser().then( - (user: CometChat.User) => { - if (!user) { - CometChat.login(authToken).then( - (user: CometChat.User) => { - console.log("Login Successful:", { user }); - }, - (error: CometChat.CometChatException) => { - console.log("Login failed with exception:", { error }); + }, + (error) => { + console.log("Something went wrong", error); + } + ); + ``` + + + ```typescript + var authToken: string = "AUTH_TOKEN"; + + // Check if user is already logged in before calling login + CometChat.getLoggedinUser().then( + (user: CometChat.User) => { + if (!user) { + CometChat.login(authToken).then( + (user: CometChat.User) => { + console.log("Login Successful:", user); + }, + (error: CometChat.CometChatException) => { + console.log("Login failed with exception:", error); + } + ); } - ); - } - }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); - } -); -``` - - - + }, + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", error); + } + ); + ``` + | Parameter | Description | @@ -162,37 +206,112 @@ CometChat.getLoggedinUser().then( After the user logs in, their information is returned in the `User` object on the `Promise` resolved. + +**On Success** — `console.log("Login Successful:", user)` returns: +```json +Login Successful: { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "authToken": "cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771311515, + "role": "default", + "status": "online", + "tags": [] +} +``` + +**On Failure** — `console.log("Login failed with exception:", error)` returns: +```json +Login failed with exception: { + "code": "ERR_AUTH_TOKEN_NOT_FOUND", + "name": "Auth token not found", + "message": "The Auth Token provided is invalid or expired.", + "details": {} +} +``` + + ## Logout You can use the `logout()` method to log out the user from CometChat. We suggest you call this method once your user has been successfully logged out from your app. - -```javascript -CometChat.logout().then( - () => { - console.log("Logout completed successfully"); - }, - (error) => { - console.log("Logout failed with exception:", { error }); - } -); -``` - - + + ```javascript + CometChat.logout().then( + () => { + console.log("Logout completed successfully"); + }, + (error) => { + console.log("Logout failed with exception:", error); + } + ); + ``` + + + ```typescript + CometChat.logout().then( + (loggedOut: Object) => { + console.log("Logout completed successfully"); + }, + (error: CometChat.CometChatException) => { + console.log("Logout failed with exception:", error); + } + ); + ``` + + - -```javascript -CometChat.logout().then( - (loggedOut: Object) => { - console.log("Logout completed successfully"); - }, - (error: CometChat.CometChatException) => { - console.log("Logout failed with exception:", { error }); - } -); + +**On Success** — `console.log("Logout completed successfully")` returns: +``` +Logout completed successfully ``` - - - +**On Failure** — `console.log("Logout failed with exception:", error)` returns: +```json +Logout failed with exception: { + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + + + + + - Always check for an existing session with `getLoggedinUser()` before calling `login()` + - Use Auth Token (not Auth Key) in production environments + - Generate Auth Tokens server-side and never expose your REST API Key in client code + - Call `logout()` when the user logs out of your app to clean up the CometChat session + - Handle login errors gracefully and provide user-friendly error messages + + + - **Login fails with "UID not found":** Ensure the user has been created in CometChat before attempting login + - **Auth Token expired:** Generate a new Auth Token from your server and retry login + - **Session persists after logout:** Ensure `logout()` completes successfully before redirecting + - **Multiple login calls:** Use `getLoggedinUser()` to prevent redundant login attempts + + + +## Next Steps + + + + Listen for real-time login and logout events + + + Start sending text, media, and custom messages + + + Track real-time online/offline status of users + + + Add pre-built UI components to your app + + diff --git a/sdk/react-native/block-users.mdx b/sdk/react-native/block-users.mdx index a56000e99..1b3528b24 100644 --- a/sdk/react-native/block-users.mdx +++ b/sdk/react-native/block-users.mdx @@ -1,8 +1,27 @@ --- title: "Block Users" +description: "Block and unblock users, and retrieve blocked user lists using the CometChat React Native SDK." --- + +**Quick Reference** - Block and unblock users: +```javascript +// Block users +await CometChat.blockUsers(["UID1", "UID2"]); + +// Unblock users +await CometChat.unblockUsers(["UID1", "UID2"]); + +// Fetch blocked users +const request = new CometChat.BlockedUsersRequestBuilder().setLimit(30).build(); +const blockedUsers = await request.fetchNext(); +``` + + + +**Available via:** [SDK](/sdk/react-native/block-users) | [REST API](/rest-api/blocked-users/block-user) + ## Block Users @@ -11,7 +30,7 @@ title: "Block Users" You can block users using the `blockUsers()` method. Once any user is blocked, all the communication to and from the respective user will be completely blocked. You can block multiple users in a single operation. The `blockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be blocked. - + ```javascript var usersList = ["UID1", "UID2", "UID3"]; CometChat.blockUsers(usersList).then( @@ -42,6 +61,22 @@ CometChat.blockUsers(usersList).then( + +**On Success** — `blockUsers()` returns an object with each UID as key and result object as value: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `[UID]` | object | Result object for each blocked UID | See below | + +**Result Object (per UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `success` | boolean | Whether the block operation succeeded | `true` | +| `message` | string | Descriptive message about the operation | `"The user with UID cometchat-uid-7 has blocked user with UID cometchat-uid-2 successfully."` | + + + It returns a Array which contains `UID's` as the keys and "success" or "fail" as the value based on if the block operation for the `UID` was successful or not. ## Unblock Users @@ -51,7 +86,7 @@ It returns a Array which contains `UID's` as the keys and "success" or "fail" as You can unblock the already blocked users using the `unblockUsers()` method. You can unblock multiple users in a single operation. The `unblockUsers()` method takes a `Array` as a parameter which holds the list of `UID's` to be unblocked. - + ```javascript var usersList = ["UID1", "UID2", "UID3"]; @@ -83,6 +118,22 @@ CometChat.unblockUsers(usersList).then( + +**On Success** — `unblockUsers()` returns an object with each UID as key and result object as value: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `[UID]` | object | Result object for each unblocked UID | See below | + +**Result Object (per UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `success` | boolean | Whether the unblock operation succeeded | `true` | +| `message` | string | Descriptive message about the operation | `"The user with UID cometchat-uid-7 has unblocked user with UID cometchat-uid-2 successfully."` | + + + It returns a Array which contains `UID's` as the keys and `success` or `fail` as the value based on if the unblock operation for the `UID` was successful or not. ## Get List of Blocked Users @@ -98,7 +149,7 @@ The `BlockedUsersRequestBuilder` class allows you to set the below parameters: This method sets the limit i.e. the number of blocked users that should be fetched in a single iteration. - + ```javascript let limit = 30; let blockedUsersRequest = new BlockedUsersRequest.BlockedUsersRequestBuilder() @@ -125,7 +176,7 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs This method allows you to set the search string based on which the blocked users are to be fetched. - + ```javascript let limit = 30; let searchKeyword = "super"; @@ -151,6 +202,26 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs + +**On Success** — `fetchNext()` with search filter returns an array of blocked `User` objects matching the search: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | +| `name` | string | Display name of the user | `"George Alan"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772104172` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772173462` | +| `blockedAt` | number | Timestamp of block action | `1772173462` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-2_user_cometchat-uid-6"` | + + + ### Set Direction * CometChat.BlockedUsersRequest.directions.BLOCKED\_BY\_ME - This will ensure that the list of blocked users only contains the users blocked by the logged in user. @@ -158,7 +229,7 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs * CometChat.BlockedUsersRequest.directions.BOTH - This will make sure the list of users includes both the above cases. This is the default value for the direction variable if it is not set. - + ```javascript let limit = 30; let blockedUsersRequest = new BlockedUsersRequest.BlockedUsersRequestBuilder() @@ -182,12 +253,57 @@ let blockedUsersRequest: CometChat.BlockedUsersRequest = new CometChat.BlockedUs + +**On Success** — `fetchNext()` with `BLOCKED_BY_ME` direction returns users blocked by the logged-in user: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | +| `name` | string | Display name of the user | `"George Alan"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772104172` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772173462` | +| `blockedAt` | number | Timestamp of block action | `1772173462` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-2_user_cometchat-uid-6"` | + + + + +**On Success** — `fetchNext()` with `HAS_BLOCKED_ME` direction returns users who have blocked the logged-in user. Returns an empty array if no users have blocked you. + + + + +**On Success** — `fetchNext()` with `BOTH` direction returns all blocked users (both directions): + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | +| `name` | string | Display name of the user | `"George Alan"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772104172` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772173462` | +| `blockedAt` | number | Timestamp of block action | `1772173462` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-2_user_cometchat-uid-6"` | + + + Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `BlockedUsersRequest` class. Once you have the object of the `BlockedUsersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `User` objects containing n number of blocked users where N is the limit set in the builder class. - + ```javascript var limit = 30; var blockedUsersRequest = new CometChat.BlockedUsersRequestBuilder() @@ -223,3 +339,65 @@ blockedUsersRequest.fetchNext().then( + + +**On Success** — `fetchNext()` returns an array of blocked `User` objects: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"123456"` | +| `name` | string | Display name of the user | `"Farhan Ahmed"` | +| `avatar` | string | URL to user's avatar image | `"https://st2.depositphotos.com/38197074/46684/v/450/depositphotos_466848082-stock-illustration-initial-letter-vector-logo.jpg"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"extrarole"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1768988601` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `metadata` | object | Custom metadata attached to the user | `{"meta": "anyValue"}` | +| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772164515` | +| `blockedAt` | number | Timestamp of block action | `1772164515` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"123456_user_cometchat-uid-7"` | + + + +## Best Practices + + + + When displaying user lists in your app, use `hideBlockedUsers(true)` in the `UsersRequestBuilder` to automatically exclude blocked users from the results. + + + The `blockUsers()` and `unblockUsers()` methods return a map with each UID's result ("success" or "fail"). Check individual results rather than assuming all operations succeeded. + + + +## Troubleshooting + + + + Blocking is enforced server-side. If a blocked user's messages still appear, verify the block operation returned "success" for that UID. Also ensure you're not using a cached conversation list — refresh after blocking. + + + Check the `setDirection` filter. If set to `BLOCKED_BY_ME`, only users you blocked are returned. If set to `HAS_BLOCKED_ME`, only users who blocked you are returned. Use `BOTH` to see all. + + + +--- + +## Next Steps + + + + Fetch user lists with filtering and pagination + + + Create, update, and delete users in CometChat + + + Track online/offline status of users in real time + + + Send text, media, and custom messages to users and groups + + \ No newline at end of file diff --git a/sdk/react-native/call-logs.mdx b/sdk/react-native/call-logs.mdx index c96177a84..e802a7ebb 100644 --- a/sdk/react-native/call-logs.mdx +++ b/sdk/react-native/call-logs.mdx @@ -1,8 +1,27 @@ --- title: "Call Logs" +description: "Fetch, filter, and display call history in your React Native app using CometChat Calls SDK — including call duration, participants, direction, and recording status." --- + +**Quick Reference** - Fetch call logs: +```javascript +const loggedInUser = await CometChat.getLoggedinUser(); + +let callLogRequest = new CometChatCalls.CallLogRequestBuilder() + .setLimit(30) + .setAuthToken(loggedInUser.getAuthToken()) + .setCallCategory("call") + .build(); + +const callLogs = await callLogRequest.fetchNext(); +``` + + + +**Available via:** [SDK](/sdk/react-native/call-logs) | [REST API](/rest-api/list-calls) | [UI Kits](/ui-kit/react/call-features#call-logs) + ## Overview @@ -40,7 +59,7 @@ let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() ### Fetch Next -The**`fetchNext()`**method retrieves the next set of call logs. +The `fetchNext()` method retrieves the next set of call logs. ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -58,9 +77,159 @@ callLogRequestBuilder.fetchNext() }); ``` + +**On Success** — `fetchNext()` returns an array of `CallLog` objects: + + + +**CallLog Array:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of call log objects | [See below ↓](#call-log-object) | + + + +**CallLog Object (each item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sessionId` | string | Unique session identifier | `"v1.in.2748663902141719.1772100619..."` | +| `totalAudioMinutes` | number | Total audio duration in minutes | `7.65` | +| `totalVideoMinutes` | number | Total video duration in minutes | `0` | +| `totalDuration` | string | Formatted total duration | `"00:07:39"` | +| `totalDurationInMinutes` | number | Total duration in minutes | `7.65` | +| `hasRecording` | boolean | Whether call has recordings | `true` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772100619` | +| `startedAt` | number | Unix timestamp when call started | `1772100622` | +| `endedAt` | number | Unix timestamp when call ended | `1772101081` | +| `initiator` | object | User who initiated the call | [See below ↓](#call-log-initiator-object) | +| `receiver` | object | User who received the call | [See below ↓](#call-log-receiver-object) | +| `mode` | string | Call mode | `"call"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `status` | string | Call status | `"ended"` | +| `totalParticipants` | number | Total number of participants | `2` | +| `type` | string | Type of call | `"audio"` | +| `mid` | string | Message ID | `"21d6e797-1b44-4a70-be73-d915dba206c7"` | +| `participants` | array | List of call participants | [See below ↓](#call-log-participants-array) | +| `recordings` | array | List of recordings | [See below ↓](#call-log-recordings-array) | +| `data` | object | Additional call data | [See below ↓](#call-log-data-object) | + +--- + + + +**`initiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user identifier | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | + +--- + + + +**`participants` Array:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of participant objects | [See below ↓](#call-log-participant-object) | + + + +**Participant Object (each item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique user identifier | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `totalAudioMinutes` | number | User's audio duration in minutes | `7.65` | +| `totalVideoMinutes` | number | User's video duration in minutes | `0` | +| `totalDurationInMinutes` | number | User's total duration in minutes | `7.65` | +| `isJoined` | boolean | Whether user joined the call | `true` | +| `state` | string | Participant state | `"ended"` | +| `deviceId` | string | Device identifier | `"2b1d0b90-b6b9-4c1c-9899-9bf4effe549f@..."` | +| `joinedAt` | number | Unix timestamp when user joined | `1772100622` | +| `leftAt` | number | Unix timestamp when user left | `1772101081` | +| `mid` | string | Message ID | `"21d6e797-1b44-4a70-be73-d915dba206c7"` | + +--- + + + +**`recordings` Array:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of recording objects | [See below ↓](#call-log-recording-object) | + + + +**Recording Object (each item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `rid` | string | Recording ID | `"noujausedimwfhwl"` | +| `recording_url` | string | URL to download the recording | `"https://recordings-in.cometchat.io/..."` | +| `duration` | number | Recording duration in minutes | `1.045` | +| `startTime` | number | Unix timestamp when recording started | `1772100632` | +| `endTime` | number | Unix timestamp when recording ended | `1772100634` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entities` | object | Entity details for the call | [See below ↓](#call-log-data-entities-object) | + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `initiator` | object | Initiator entity wrapper | [See below ↓](#call-log-data-entities-initiator) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#call-log-data-entities-receiver) | + + + +**`data.entities.initiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | User entity details | `{"uid": "cometchat-uid-7", "name": "Henry Marino", "avatar": "..."}` | + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | User entity details | `{"uid": "cometchat-uid-6", "name": "Ronald Jerry", "avatar": "..."}` | + + + ### Fetch Previous -The**`fetchPrevious()`**method retrieves the previous set of call logs. +The `fetchPrevious()` method retrieves the previous set of call logs. ```javascript let callLogRequestBuilder = new CometChatCalls.CallLogRequestBuilder() @@ -78,9 +247,13 @@ callLogRequestBuilder.fetchPrevious() }); ``` + +**On Success** — `fetchPrevious()` returns an array of `CallLog` objects with the same structure as `fetchNext()`. See [fetchNext Response](#call-log-array) for the complete object structure. + + ## Get Call Details -To retrieve the specific details of a call, use the**`getCallDetails()`**method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. +To retrieve the specific details of a call, use the `getCallDetails()` method. This method requires the Auth token of the logged-in user and the session ID along with a callback listener. ```javascript var sessionID = "SESSION_ID"; @@ -93,4 +266,57 @@ CometChatCalls.getCallDetails(sessionID, authToken) }); ``` -Note: Replace**`"SESSION_ID"`**with the ID of the session you are interested in. + +**On Success** — `getCallDetails()` returns an array of `CallLog` objects with the same structure as `fetchNext()`. See [fetchNext Response](#call-log-array) for the complete object structure. + + + +Replace `"SESSION_ID"` with the ID of the session you are interested in. + + +## Best Practices + + + + Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30) rather than fetching all logs at once. This improves performance and reduces memory usage, especially for users with extensive call histories. + + + Use the builder's filter methods (`setCallType`, `setCallStatus`, `setCallDirection`) to fetch only the logs relevant to your current UI view. For example, show only missed calls in a "Missed" tab rather than filtering client-side. + + + Consider caching fetched call logs locally to reduce API calls and improve load times. Use `fetchNext()` to load newer logs and `fetchPrevious()` for older ones as the user scrolls. + + + +## Troubleshooting + + + + Verify that the `authToken` passed to `setAuthToken()` is valid and belongs to the logged-in user. Also check that calls have actually been made — call logs are only generated after a call session completes. + + + Ensure you're reusing the same `callLogRequestBuilder` instance for pagination. Creating a new builder resets the cursor, causing the same page to be fetched repeatedly. + + + Confirm the `sessionID` is correct and corresponds to a completed call. Active or in-progress calls may not have full details available yet. + + + +--- + +## Next Steps + + + + Implement a complete calling experience with incoming and outgoing call UI + + + Start and manage call sessions with full configuration options + + + Record call sessions for playback and compliance + + + Implement calling without the Chat SDK + + \ No newline at end of file diff --git a/sdk/react-native/calling-overview.mdx b/sdk/react-native/calling-overview.mdx index f8ec2136f..12683a7c5 100644 --- a/sdk/react-native/calling-overview.mdx +++ b/sdk/react-native/calling-overview.mdx @@ -1,15 +1,35 @@ --- title: "Calling" sidebarTitle: "Overview" +description: "Add voice and video calling to your React Native app with CometChat. Choose between Ringing, Call Session, or Standalone implementations." --- + +**Quick Reference** - Install the Calls SDK and initialize: + +```javascript +npm install @cometchat/calls-sdk-react-native + +// Initialize CometChatCalls +const callAppSettings = new CometChatCalls.CallAppSettingsBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .build(); +await CometChatCalls.init(callAppSettings); +``` + + + +Available via: [SDK](/sdk/react-native/calling-overview) | [REST API](/rest-api/calls) | [UI Kits](/ui-kit/react-native/call-features) + + ## Overview CometChat provides voice and video calling capabilities for your React Native application. This guide helps you choose the right implementation approach based on your use case. ## Prerequisites -1. CometChat SDK installed and configured. See the [Setup](/sdk/react-native/overview) guide. +1. CometChat SDK installed and configured. See the [Setup](/sdk/react-native/setup-sdk) guide. 2. CometChat Calls SDK added to your project: ```bash @@ -87,3 +107,37 @@ Use this when you want: Configure automatic call termination when participants are inactive. + + + + - Initialize `CometChatCalls` on app startup, right after `CometChat.init()` + - Use the Ringing flow for user-to-user calls where you need push notification support + - Use Call Session when building custom call UIs or conference-style experiences + - Always request camera and microphone permissions before initiating a call + - Handle call errors gracefully and provide user-friendly feedback + + + - **Calls not connecting:** Verify the Calls SDK is initialized after the Chat SDK and that both use the same App ID and Region + - **No audio/video:** Check that camera and microphone permissions are granted on both Android and iOS + - **Push notifications not arriving:** Ensure push notification setup is complete — see the [Push Notifications](/sdk/react-native/push-notification) guide + - **iOS build fails:** Run `pod install` in the `ios` directory after adding the Calls SDK dependency + - **Android minSdkVersion error:** Set `minSdkVersion` to 24 or higher in your `build.gradle` + + + +## Next Steps + + + + Install dependencies, configure permissions, and initialize the Calls SDK. + + + Implement the complete incoming/outgoing call experience. + + + Manage call sessions with custom initiation logic. + + + Retrieve and display call history for your users. + + diff --git a/sdk/react-native/calling-setup.mdx b/sdk/react-native/calling-setup.mdx index f8483f5ca..bd2de66f1 100644 --- a/sdk/react-native/calling-setup.mdx +++ b/sdk/react-native/calling-setup.mdx @@ -1,8 +1,23 @@ --- title: "Setup" +description: "Install and configure the CometChat Calls SDK for React Native, including dependencies, platform permissions, and initialization." --- + +**Quick Reference** - Install and initialize the Calls SDK: +```javascript +npm install @cometchat/calls-sdk-react-native + +// Initialize on app startup +import { CometChatCalls } from "@cometchat/calls-sdk-react-native"; +const callAppSettings = new CometChatCalls.CallAppSettingsBuilder() + .setAppId("APP_ID") + .setRegion("REGION") + .build(); +await CometChatCalls.init(callAppSettings); +``` + ## Get your Application Keys @@ -56,7 +71,7 @@ The CometChat Calls SDK also requires the below dependencies to be installed. -If you’re using Expo, please refer to the [Expo Integration Guide](/sdk/react-native/expo-integration-guide) for setting up permissions. +If you're using Expo, please refer to the [Expo Integration Guide](/sdk/react-native/expo-integration-guide) for setting up permissions. @@ -138,7 +153,7 @@ The `CallAppSettings` class allows you to configure three settings: * **Region**: The region where you app was created. * **Host(host: string)**: This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat. -You need to call `init()` before calling any other method from CometChatCalls. We suggest you call the `init()` method on app startup, preferably in the `index.js` file. +You need to call `init()` before calling any other method from CometChatCalls. We suggest you call the `init()` method on app startup, preferably in the `App.tsx` file. @@ -191,8 +206,44 @@ CometChatCalls.init(callAppSetting).then( + Make sure you replace the `APP_ID` with your CometChat `AppID` and `REGION` with your **App Region** in the above code. + | Parameter | Description | | ----------------- | ---------------------------------------- | | `callAppSettings` | An object of the `CallAppSettings` class | + + + + - Initialize `CometChatCalls` right after `CometChat.init()` on app startup + - Always call `CometChatCalls.init()` before using any calling methods + - Request camera and microphone permissions at runtime before initiating calls + - Use the correct `netinfo` version based on your React Native version (0.63+ vs below) + - Run `pod install` after adding dependencies to ensure iOS native modules are linked + + + - **Initialization fails:** Verify your App ID and Region match the values in your CometChat Dashboard + - **Android build fails:** Ensure `minSdkVersion` is set to 24 or higher in `build.gradle` + - **iOS build fails:** Run `pod install` in the `ios` directory and open the `.xcworkspace` file (not `.xcodeproj`) + - **Permission denied errors:** Confirm camera and microphone permissions are declared in `AndroidManifest.xml` and `Info.plist` + - **Module not found:** Make sure all required peer dependencies are installed — check the dependency list above + + + +## Next Steps + + + + Choose the right calling implementation for your use case. + + + Implement the complete incoming/outgoing call experience. + + + Manage call sessions with custom initiation logic. + + + Record audio and video calls for playback or compliance. + + diff --git a/sdk/react-native/connection-status.mdx b/sdk/react-native/connection-status.mdx index 4733f7fa1..d6dc91ab0 100644 --- a/sdk/react-native/connection-status.mdx +++ b/sdk/react-native/connection-status.mdx @@ -1,8 +1,23 @@ --- title: "Connection Status" +description: "Learn how to monitor the real-time WebSocket connection status using the CometChat React Native SDK, including connecting, connected, and disconnected states." --- - + +**Quick Reference** +```javascript +// Listen for connection status changes +CometChat.addConnectionListener("listenerId", new CometChat.ConnectionListener({ + onConnected: () => {}, + inConnecting: () => {}, + onDisconnected: () => {} +})); + +// Get current connection status +var status = CometChat.getConnectionStatus(); +// Returns: "connecting" | "connected" | "disconnected" +``` + CometChat SDK provides you with a mechanism to get real-time status of the connection to CometChat web-socket servers. @@ -19,7 +34,7 @@ Once the connection is broken, the disconnected callback is triggered, the SDK a To receive real-time connection status, you need to register `ConnectionListener` wherever you wish to receive the real-time status. You can use the `addConnectionListener()` method to do so. - + ```javascript var listenerID = "UNIQUE_LISTENER_ID"; CometChat.addConnectionListener( @@ -69,16 +84,21 @@ CometChat.addConnectionListener( - - -We recommend you to add the Connection Listener in your method on app startup, preferably in the index.js file. Once you have successfully initialized CometChat. + +Always remove connection listeners when the component unmounts to prevent memory leaks. +```javascript +CometChat.removeConnectionListener("UNIQUE_LISTENER_ID"); +``` + + +We recommend you to add the Connection Listener in your method on app startup, preferably in the App.tsx file. Once you have successfully initialized CometChat. You can also get the current connection status by using `getConnectionStatus` property provided by CometChat SDK - + ```javascript var connectionStatus = CometChat.getConnectionStatus(); ``` @@ -94,8 +114,35 @@ var connectionStatus: string = CometChat.getConnectionStatus(); -The `CometChat.getConnectionStatus` method will return either of the below 4 values: - -1. connecting -2. connected -3. disconnected +The `CometChat.getConnectionStatus` method will return either of the below 3 values: + +1. `connecting` +2. `connected` +3. `disconnected` + + + +- Register the connection listener early in your app lifecycle (after `CometChat.init()`) to catch connection state changes from the start +- Use connection status to show a connectivity indicator in your UI (e.g., a banner when disconnected) +- When the status changes to `connected` after a `disconnected` state, consider refreshing your message list to fetch any messages missed during the disconnection +- Avoid making SDK calls (sending messages, fetching data) while the status is `disconnected` — queue them and retry once `connected` + + + +- **Listener not firing**: Ensure you registered the `ConnectionListener` with a unique listener ID after calling `CometChat.init()`. +- **Stuck in connecting state**: Check your network connection and verify that the App ID and region are correct in your `AppSettings`. +- **Frequent disconnections**: This is typically caused by network instability. The SDK handles reconnection automatically in auto mode. +- **`onFeatureThrottled` firing**: This indicates your app is hitting rate limits. Reduce the frequency of API calls. + + + +## Next Steps + + + +Take full control of WebSocket connections + + +Register listeners for users, groups, messages, and calls + + diff --git a/sdk/react-native/create-group.mdx b/sdk/react-native/create-group.mdx index 025dd887e..b6090b5bc 100644 --- a/sdk/react-native/create-group.mdx +++ b/sdk/react-native/create-group.mdx @@ -1,8 +1,25 @@ --- title: "Create A Group" +description: "Create public, private, or password-protected groups in CometChat React Native SDK, with optional member and ban lists at creation time." --- + +**Quick Reference** - Create a group: +```javascript +// Create a public group +const group = new CometChat.Group("GUID", "Hello Group!", CometChat.GROUP_TYPE.PUBLIC, ""); +await CometChat.createGroup(group); + +// Create with members +const members = [new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT)]; +await CometChat.createGroupWithMembers(group, members, []); +``` + + + +**Available via:** [SDK](/sdk/react-native/create-group) | [REST API](/rest-api/groups/create) | [UI Kits](/ui-kit/react-native/groups) + ## Create a Group @@ -24,7 +41,7 @@ The `groupType` needs to be either of the below 3 values: 3.`CometChat.GROUP_TYPE.PRIVATE` - + ```javascript var GUID = "GUID"; var groupName = "Hello Group!"; @@ -76,7 +93,7 @@ After successful creation of the group, you will receive an instance of `Group` -GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. +GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. CometChat automatically converts any uppercase characters in the GUID to lowercase. @@ -171,3 +188,50 @@ This method returns an Object which has two keys: `group` & `members` . The grou | scope | Yes | Scope of the logged in user. Can be: 1. Admin 2. Moderator 3. Participant | | membersCount | No | The number of members in the groups | | tags | Yes | A list of tags to identify specific groups. | + +## Best Practices + + + + If you know the initial members at creation time, use `createGroupWithMembers()` instead of creating the group first and then adding members separately. This reduces API calls and ensures atomic group setup. + + + Use the same group identifier from your backend as the CometChat GUID. This simplifies mapping between your system and CometChat. + + + The `createGroupWithMembers()` response includes per-UID results ("success" or error). Check each result rather than assuming all members were added successfully. + + + +## Troubleshooting + + + + Each GUID must be unique across your CometChat app. If the group already exists, use a different GUID or retrieve the existing group with `getGroup()`. + + + GUIDs can only contain alphanumeric characters, underscores, and hyphens. Spaces, punctuation, and other special characters are not allowed. Uppercase characters are automatically converted to lowercase. + + + Check the `members` key in the response object for per-UID error messages. Common causes include invalid UIDs or users that don't exist in your CometChat app. + + + +--- + +## Next Steps + + + + Fetch group lists, search groups, and get group details + + + Join public or password-protected groups + + + Manage members, roles, and permissions within groups + + + Send text, media, and custom messages to groups + + \ No newline at end of file diff --git a/sdk/react-native/default-call.mdx b/sdk/react-native/default-call.mdx index baa178f5b..a44b1d3db 100644 --- a/sdk/react-native/default-call.mdx +++ b/sdk/react-native/default-call.mdx @@ -1,7 +1,28 @@ --- title: "Ringing" +description: "Implement a complete calling workflow with ringing, incoming/outgoing call UI, accept, reject, and cancel functionality in CometChat React Native SDK." --- + +**Quick Reference** - Initiate a call and listen for events: + +```javascript +// Initiate a video call +const call = new CometChat.Call("RECEIVER_ID", CometChat.CALL_TYPE.VIDEO, CometChat.RECEIVER_TYPE.USER); +await CometChat.initiateCall(call); + +// Accept an incoming call +await CometChat.acceptCall(sessionId); + +// Reject or cancel +await CometChat.rejectCall(sessionId, CometChat.CALL_STATUS.REJECTED); +``` + + + +Available via: [SDK](/sdk/react-native/default-call) | [REST API](/rest-api/calls) | [UI Kits](/ui-kit/react-native/call-features) + + ## Overview This section explains how to implement a complete calling workflow with ringing functionality, including incoming/outgoing call UI, call acceptance, rejection, and cancellation. Previously known as **Default Calling**. @@ -18,7 +39,7 @@ After the call is accepted, you need to start the call session. See the [Call Se - Accept the call using `acceptCall()` - Reject the call using `rejectCall()` with status `CALL_STATUS_REJECTED` 4. **Caller** can cancel the call using `rejectCall()` with status `CALL_STATUS_CANCELLED` -5. Once accepted, both participants call `startSession()` to join the call +5. Once accepted, both participants generate a call token and render the `CometChatCalls.Component` to join the call ## Initiate Call @@ -110,6 +131,7 @@ CometChat.initiateCall(call).then( On success, a `Call` object is returned containing the call details including a unique `sessionId` required for starting the call session. + ## Call Listeners Register the `CallListener` to receive real-time call events. Each listener requires a unique `listenerId` string to prevent duplicate registrations and enable targeted removal. @@ -187,6 +209,10 @@ CometChat.removeCallListener(listenerId); + +Always remove call listeners when the component unmounts using `CometChat.removeCallListener(listenerId)`. Failing to do so can cause memory leaks and duplicate event handling. + + ### Events | Event | Description | @@ -197,6 +223,7 @@ CometChat.removeCallListener(listenerId); | `onIncomingCallCancelled(call)` | Invoked on the receiver's device when the caller cancels before answering. Dismiss incoming call UI here. | | `onCallEndedMessageReceived(call)` | Invoked when a call ends. The `call` contains final status and duration. Update call history here. | + ## Accept Call When an incoming call is received via `onIncomingCallReceived()`, use `acceptCall()` to accept it. On success, start the call session. @@ -311,6 +338,7 @@ CometChat.rejectCall(sessionId, status).then( + ## Start Call Session Once the call is accepted, both participants need to start the call session. @@ -416,6 +444,7 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( For more details on call settings and customization, see the [Call Session](/sdk/react-native/direct-call#start-call-session) guide. + ## End Call To end an active call in the ringing flow, the process differs based on who ends the call. @@ -522,3 +551,40 @@ CometChat.rejectCall(sessionId, status).then( ``` + + + + + - Always remove call listeners on component unmount to prevent memory leaks and duplicate events + - Store the `sessionId` from `initiateCall()` or `onIncomingCallReceived()` — you'll need it for accept, reject, cancel, and starting the session + - Handle the `CALL_STATUS_BUSY` case when the receiver is already on another call + - Call `CometChat.clearActiveCall()` and `CometChatCalls.endSession()` together when a call ends to properly release all resources + - Request camera and microphone permissions before initiating or accepting a call + - Show appropriate UI feedback (spinner, ringing animation) while waiting for the receiver to respond + + + - **`onIncomingCallReceived` not firing:** Ensure `CometChat.addCallListener()` is registered before the call is initiated and that the listener ID is unique + - **Call accepted but no audio/video:** After `acceptCall()`, you must start the call session by generating a token and rendering `CometChatCalls.Component` — see the Start Call Session section above + - **Duplicate call events:** You may have registered the same listener multiple times — always call `CometChat.removeCallListener(listenerId)` on unmount + - **`initiateCall` fails with error:** Verify the receiver UID/GUID exists and that the logged-in user has an active session + - **Call ends immediately after accept:** Make sure both caller and receiver generate a call token and render `CometChatCalls.Component` — if only one side renders the component, the call will appear to drop + - **Busy status not working:** Ensure you're using `CometChat.CALL_STATUS.BUSY` (not `REJECTED`) when the receiver is already on a call + + + +## Next Steps + + + + Start and manage the actual call session after the ringing flow completes. + + + Install dependencies, configure permissions, and initialize the Calls SDK. + + + Record audio and video calls for playback or compliance. + + + Retrieve and display call history including duration and participants. + + diff --git a/sdk/react-native/delete-conversation.mdx b/sdk/react-native/delete-conversation.mdx index 886bc7c50..f8fafef7a 100644 --- a/sdk/react-native/delete-conversation.mdx +++ b/sdk/react-native/delete-conversation.mdx @@ -1,15 +1,33 @@ --- title: "Delete A Conversation" +description: "Learn how to delete user and group conversations for the logged-in user using the CometChat React Native SDK." --- + +**Quick Reference** +```javascript +// Delete a user conversation +CometChat.deleteConversation("UID", "user"); + +// Delete a group conversation +CometChat.deleteConversation("GUID", "group"); +``` + + +**Available via:** [SDK](/sdk/react-native/delete-conversation) | [REST API](/rest-api/conversations/reset-user-conversation) | [UI Kits](/ui-kit/react-native/overview) + In case you want to delete a conversation, you can use the `deleteConversation()` method. -This method takes two parameters. The unique id (UID/GUID) of the conversation to be deleted & the type (user/group) of conversation to be deleted. +This method takes two parameters: the unique ID (UID/GUID) of the conversation to be deleted, and the type (`user`/`group`) of conversation to be deleted. + + +Deleting a conversation is an irreversible operation for the logged-in user. Once deleted, the conversation and its associated data cannot be recovered for that user. + - + ```javascript let UID = "UID"; let type = "user"; @@ -24,7 +42,7 @@ CometChat.deleteConversation(UID, type).then( - + ```javascript let GUID = "GUID"; let type = "group"; @@ -39,7 +57,7 @@ CometChat.deleteConversation(GUID, type).then( - + ```typescript let UID: string = "UID"; let type: string = "user"; @@ -54,7 +72,7 @@ CometChat.deleteConversation(UID, type).then( - + ```typescript let GUID: string = "GUID"; let type: string = "group"; @@ -71,6 +89,13 @@ CometChat.deleteConversation(GUID, type).then( + +**On Success** — `deleteConversation()` returns a success message: +```json +"Conversation deleted successfully." +``` + + This method deletes the conversation only for the logged-in user. To delete a conversation for all the users of the conversation, please refer to our REST API documentation [here](https://api-explorer.cometchat.com/reference/deletes-conversation). The `deleteConversation()` method takes the following parameters: @@ -78,4 +103,34 @@ The `deleteConversation()` method takes the following parameters: | Parameter | Description | Required | | ---------------- | --------------------------------------------------------------------------------- | -------- | | conversationWith | `UID` of the user or `GUID` of the group whose conversation you want to delete. | YES | -| conversationType | The type of conversation you want to delete . It can be either `user` or `group`. | YES | +| conversationType | The type of conversation you want to delete. It can be either `user` or `group`. | YES | + + + + - Always confirm with the user before deleting a conversation, as this action is irreversible for the logged-in user. + - Handle the error callback gracefully to inform users if the deletion fails (e.g., due to network issues or invalid IDs). + - After a successful deletion, update your local conversation list by refreshing it using `ConversationsRequest`. + + + - **Conversation not found**: Ensure the `UID` or `GUID` you are passing is correct and that a conversation with that user or group exists. + - **Permission denied**: Verify that the logged-in user has the appropriate permissions and that the SDK is initialized and the user is logged in. + - **Type mismatch**: Make sure the `conversationType` parameter matches the ID you are passing — use `"user"` with a `UID` and `"group"` with a `GUID`. + + + +## Next Steps + + + + Fetch and display the list of conversations for the logged-in user. + + + Remove individual messages from a conversation. + + + Listen for and handle incoming real-time messages. + + + Explore the full set of messaging capabilities available in the SDK. + + diff --git a/sdk/react-native/delete-group.mdx b/sdk/react-native/delete-group.mdx index 8ed2c7cf3..f877d325f 100644 --- a/sdk/react-native/delete-group.mdx +++ b/sdk/react-native/delete-group.mdx @@ -1,15 +1,26 @@ --- title: "Delete A Group" +description: "Delete groups using the CometChat React Native SDK — requires Admin scope on the group." --- + +**Quick Reference** - Delete a group: +```javascript +await CometChat.deleteGroup("GUID"); +``` + + + +**Available via:** [SDK](/sdk/react-native/delete-group) | [REST API](/rest-api/delete-group) + ## Delete a Group To delete a group you need to use the `deleteGroup()` method. The user must be an `Admin` of the group they are trying to delete. - + ```javascript var GUID = "GUID"; @@ -46,3 +57,44 @@ The `deleteGroup()` method takes the following parameters: | Parameter | Description | | --------- | ---------------------------------------------- | | `GUID` | The GUID of the group you would like to delete | + +## Best Practices + + + + Deleting a group is irreversible — all messages, members, and metadata are permanently removed. Always prompt the user for confirmation before calling `deleteGroup()`. + + + The logged-in user must have Admin scope on the group. Verify the user's scope using `getGroup()` before attempting deletion to provide a better UX. + + + +## Troubleshooting + + + + Verify the logged-in user is an Admin of the group. Owners and Moderators may not have delete permissions depending on your app configuration. + + + Ensure the `deleteGroup()` promise resolved successfully. If using cached data, refresh your group list after deletion to remove stale entries. + + + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Fetch group lists, search groups, and get group details + + + Leave groups and stop receiving updates + + + Transfer group ownership before leaving + + \ No newline at end of file diff --git a/sdk/react-native/delete-message.mdx b/sdk/react-native/delete-message.mdx index 0a21fbff8..fb3d013df 100644 --- a/sdk/react-native/delete-message.mdx +++ b/sdk/react-native/delete-message.mdx @@ -1,22 +1,48 @@ --- title: "Delete A Message" +description: "Learn how to delete messages, listen for real-time message delete events, and retrieve missed message deletions using the CometChat React Native SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Delete a message by ID +let messageId = "MESSAGE_ID"; +CometChat.deleteMessage(messageId).then( + (message) => console.log("Message deleted", message), + (error) => console.log("Delete failed:", error) +); + +// Listen for real-time message deletes +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onMessageDeleted: (message) => console.log("Deleted:", message) +})); +``` + While [deleting a message](/sdk/react-native/delete-message#delete-a-message) is straightforward, receiving events for deleted messages with CometChat has two parts: 1. Adding a listener to receive [real-time message deletes](/sdk/react-native/delete-message#real-time-message-delete-events) when your app is running. 2. Calling a method to retrieve [missed message deletes](/sdk/react-native/delete-message#missed-message-delete-events) when your app was not running. + +**Available via:** [SDK](/sdk/react-native/delete-message) | [REST API](/rest-api/messages/delete-message) | [UI Kits](/ui-kit/react-native/overview) + + ## Delete a Message *In other words, as a sender, how do I delete a message?* -In case you have to delete a message, you can use the `deleteMessage()` method. This method takes the message ID of the message to be deleted. +To delete a message, use the `deleteMessage()` method. This method takes the message ID of the message to be deleted. + + +This operation is irreversible. Deleted messages cannot be recovered. + - + ```javascript let messageId = "ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE"; @@ -48,7 +74,83 @@ CometChat.deleteMessage(messageId).then( -Once the message is deleted, In the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` field set with the timestamp of the time the message was deleted. Also, the `deletedBy` field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages. + +**On Success** — `deleteMessage()` returns the deleted message object with `deletedAt` and `deletedBy` fields set: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-6", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771994056, + "name": "Ronald Jerry", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771993054, + "name": "Henry Marino", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + } + } + }, + "id": "25305", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771993054, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771994056, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771996215, + "deliveredAt": 1771996215, + "readAt": 1771996215, + "deletedAt": 1771996222, + "updatedAt": 1771996222, + "deletedBy": "cometchat-uid-7" +} +``` + + +Once the message is deleted, in the `onSuccess()` callback, you get an object of the `BaseMessage` class, with the `deletedAt` field set with the timestamp of the time the message was deleted. Also, the `deletedBy` field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages. By default, CometChat allows certain roles to delete a message. @@ -66,7 +168,7 @@ By default, CometChat allows certain roles to delete a message. In order to receive real-time events for a message being deleted, you need to override the `onMessageDeleted()` method of the `MessageListener` class. - + ```javascript var listenerID = "UNIQUE_LISTENER_ID"; @@ -100,12 +202,174 @@ CometChat.addMessageListener( + +**On Event** — `onMessageDeleted` callback receives the deleted message object: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771993054, + "name": "Henry Marino", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771994056, + "name": "Ronald Jerry", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + } + } + }, + "id": "25301", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771994056, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771993054, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771996032, + "deliveredAt": 1771996033, + "readAt": 1771996033, + "deletedAt": 1771996040, + "updatedAt": 1771996040, + "deletedBy": "cometchat-uid-6" +} +``` + + + +Always remove listeners when they are no longer needed (e.g., on component unmount or screen navigation). Failing to remove listeners can cause memory leaks and duplicate event handling. + +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Message Delete Events *In other words, as a recipient, how do I know if someone deleted a message when my app was not running?* When you retrieve the list of previous messages, for the messages that were deleted, the `deletedAt` and the `deletedBy` fields will be set. Also, for example, of the total number of messages for a conversation are 100, and the message with message ID 50 was deleted. Now the message with id 50 will have the `deletedAt` and the `deletedBy` fields set whenever it is pulled from the history. Also, the 101st message will be an Action message informing you that the message with id 50 has been deleted. + +**When fetching message history** — deleted messages have `deletedAt` and `deletedBy` fields set: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771993054, + "name": "Henry Marino", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771994056, + "name": "Ronald Jerry", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + } + } + }, + "id": "25301", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771994056, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771993054, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771996032, + "deliveredAt": 1771996033, + "readAt": 1771996033, + "deletedAt": 1771996040, + "updatedAt": 1771996040, + "deletedBy": "cometchat-uid-6" + } +] +``` + + For the message deleted event, in the `Action` object received, the following fields can help you get the relevant information- 1. `action` - `deleted` @@ -113,8 +377,46 @@ For the message deleted event, in the `Action` object received, the following fi 3. `actionBy` - User object containing the details of the user who has deleted the message. 4. `actionFor` - User/group object having the details of the receiver to which the message was sent. + +When fetching message history, deleted messages include `deletedAt` and `deletedBy` fields. You can check if `deletedAt` is set to identify deleted messages. Additionally, an Action message with `action: "deleted"` is added to the message list for audit/timeline purposes. + + -In order to edit or delete a message you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. +In order to edit or delete a message, you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. + + + + - **Check `deletedAt` when rendering messages.** Before displaying a message, check if `deletedAt` is set. If it is, show a "This message was deleted" placeholder instead of the original content. + - **Use unique listener IDs.** Use a unique identifier per screen or component (e.g., `"ChatScreen_DeleteListener"`) to avoid conflicts with other listeners. + - **Always clean up listeners.** Remove message listeners in your component's cleanup or unmount lifecycle to prevent memory leaks. + - **Handle permissions gracefully.** If a user attempts to delete a message they don't have permission to delete, handle the error callback and inform the user. + + + - **"Message delete failed" error:** Verify that the message ID is valid and that the current user has permission to delete the message (sender, group admin, or group moderator). + - **`onMessageDeleted` not firing:** Ensure you have registered the `MessageListener` with `CometChat.addMessageListener()` before the delete event occurs, and that the listener ID is unique. + - **Deleted messages still showing in the UI:** Make sure you are checking the `deletedAt` field on each message when rendering your message list, and updating your local state when `onMessageDeleted` fires. + - **Duplicate delete events:** This usually happens when multiple listeners are registered with the same or different IDs without being removed. Ensure you remove listeners on component unmount. + + + +--- + +## Next Steps + + + + Modify the content of a sent message + + + Send text, media, and custom messages + + + Listen for and retrieve incoming messages + + + Report inappropriate or unwanted messages + + diff --git a/sdk/react-native/delivery-read-receipts.mdx b/sdk/react-native/delivery-read-receipts.mdx index e6b5b9b6f..97d847e44 100644 --- a/sdk/react-native/delivery-read-receipts.mdx +++ b/sdk/react-native/delivery-read-receipts.mdx @@ -1,13 +1,38 @@ --- title: "Delivery & Read Receipts" +description: "Learn how to mark messages as delivered, read, or unread and listen for real-time receipt events using the CometChat React Native SDK." --- + +**Quick Reference** - Mark messages and listen for receipts: + +```javascript +// Mark as delivered +CometChat.markAsDelivered(message); + +// Mark as read +CometChat.markAsRead(message); +// Listen for receipts +CometChat.addMessageListener("LISTENER_ID", new CometChat.MessageListener({ + onMessagesDelivered: (receipt) => console.log("Delivered", receipt), + onMessagesRead: (receipt) => console.log("Read", receipt), +})); +``` + + + +**Available via:** [SDK](/sdk/react-native/delivery-read-receipts) | [REST API](/rest-api/conversations/mark-user-conversation-as-delivered) | [UI Kits](/ui-kit/react-native/overview) + ## Mark Messages as Delivered *In other words, as a recipient, how do I inform the sender that I've received a message?* +{/* Mark all messages up to a specified message ID as delivered. Two ways to use markAsDelivered: + 1. Pass the message object directly — CometChat.markAsDelivered(message) + 2. Pass individual params — CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId) */} + You can mark the messages for a particular conversation as read using the `markAsDelivered()` method. This method takes the below parameters as input: | Parameter | Information | @@ -25,7 +50,7 @@ Ideally, you would like to mark all the messages as delivered for any conversati 2. **When the user is on the chat window and a real-time message is received:** In this case you need to obtain the message ID of the message and pass it to the markAsDelivered() method. - + ```javascript var messageId = "MESSAGE_ID"; var receiverId = "MESSAGE_RECEIVER_UID"; @@ -36,7 +61,7 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); - + ```javascript var messageId = "MESSAGE_ID"; var receiverId = "MESSAGE_RECEIVER_GUID"; @@ -47,7 +72,7 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); - + ```typescript var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_RECEIVER_UID"; @@ -58,7 +83,7 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId); - + ```typescript var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_RECEIVER_GUID"; @@ -76,7 +101,7 @@ This method will mark all the messages before the messageId specified, for the c In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. - + ```javascript CometChat.markAsDelivered( message.getId(), @@ -98,7 +123,7 @@ CometChat.markAsDelivered( - + ```javascript CometChat.markAsDelivered( message.getId(), @@ -120,7 +145,7 @@ CometChat.markAsDelivered( - + ```typescript var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_SENDER_UID"; @@ -141,7 +166,7 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( - + ```typescript var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_RECEIVER_GUID"; @@ -167,7 +192,7 @@ CometChat.markAsDelivered(messageId, receiverId, receiverType, senderId).then( Another option the CometChat SDK provides is to pass the entire message object to the markAsDelivered() method. - + ```javascript CometChat.markAsDelivered(message); ``` @@ -187,7 +212,7 @@ CometChat.markAsDelivered(message); In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. - + ```javascript CometChat.markAsDelivered(message).then( () => { @@ -224,10 +249,24 @@ CometChat.markAsDelivered(message).then( + +**On Success** — `markAsDelivered()` returns a confirmation object: +```json +{ + "messageId": "25323", + "type": "text" +} +``` + + ## Mark Messages as Read *In other words, as a recipient, how do I inform the sender I've read a message?* +{/* Mark all messages up to a specified message ID as read. Two ways to use markAsRead: + 1. Pass the message object directly — CometChat.markAsRead(message) + 2. Pass individual params — CometChat.markAsRead(messageId, receiverId, receiverType, senderId) */} + You can mark the messages for a particular conversation as read using the `markAsRead()` method. This method takes the below parameters as input: | Parameter | Information | @@ -245,7 +284,7 @@ Ideally, you would like to mark all the messages as read for any conversation wh 2. **When the user is on the chat window and a real-time message is received:** In this case you need to obtain the message ID of the message and pass it to the markAsRead() method - + ``` var messageId = "MESSAGE_ID"; var receiverId = "MESSAGE_SENDER_UID"; @@ -256,7 +295,7 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); - + ``` var messageId = "MESSAGE_ID"; var receiverId = "MESSAGE_RECEIVER_GUID"; @@ -267,7 +306,7 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); - + ``` var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_SENDER_UID"; @@ -278,7 +317,7 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId); - + ``` var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_RECEIVER_GUID"; @@ -296,7 +335,7 @@ This method will mark all the messages before the messageId specified, for the c In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. - + ```javascript CometChat.markAsRead( message.getId(), @@ -315,7 +354,7 @@ CometChat.markAsRead( - + ```javascript CometChat.markAsRead( message.getId(), @@ -334,7 +373,7 @@ CometChat.markAsRead( - + ```typescript var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_SENDER_UID"; @@ -352,7 +391,7 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( - + ```typescript var messageId: string = "MESSAGE_ID"; var receiverId: string = "MESSAGE_RECEIVER_GUID"; @@ -375,7 +414,7 @@ CometChat.markAsRead(messageId, receiverId, receiverType, senderId).then( Another option the CometChat SDK provides is to pass the entire message object to the markAsRead() method.If the message object is the last message, the entire conversation will be marked as read. - + ```javascript CometChat.markAsRead(message); ``` @@ -395,7 +434,7 @@ CometChat.markAsRead(message); In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback)` of the `markAsDelivered` method. - + ```javascript CometChat.markAsRead(message).then( () => { @@ -426,8 +465,21 @@ CometChat.markAsRead(message).then( + +**On Success** — `markAsRead()` returns a confirmation object: +```json +{ + "messageId": "25323", + "type": "text" +} +``` + + ## Mark Messages as Unread +{/* Mark a message as unread — CometChat.markMessageAsUnread(message) + Only works for messages received from other users. Returns updated Conversation object. */} + The Mark as Unread feature allows users to designate specific messages or conversations as unread, even if they have been previously viewed. This feature is valuable for users who want to revisit and respond to important messages or conversations later, ensuring they don't forget or overlook them. @@ -445,7 +497,7 @@ You cannot mark your own messages as unread. This method only works for messages - + ```javascript CometChat.markMessageAsUnread(message); ``` @@ -465,7 +517,7 @@ CometChat.markMessageAsUnread(message); In case you would like to be notified of an error if the receipts fail to go through you can use `.then(successCallback, failureCallback).` On success, this method returns an updated `Conversation` object with the updated unread message count and other conversation data. - + ```javascript CometChat.markMessageAsUnread(message).then( (conversation) => { @@ -498,6 +550,85 @@ CometChat.markMessageAsUnread(message).then( + +**On Success** — `markMessageAsUnread()` returns the updated `Conversation` object with the new unread count: +```json +{ + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25323", + "unreadMessageCount": 1, + "lastMessage": { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1772005334, + "role": "default", + "status": "online" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "text": "Hello <@uid:cometchat-uid-7>, this is a test mention!", + "id": "25326", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1772004288, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1772005334, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1772006074, + "deliveredAt": 1772006158, + "readAt": 1772006158, + "updatedAt": 1772006158 + }, + "latestMessageId": "", + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1772004288, + "role": "default", + "status": "offline", + "tags": [], + "conversationId": "cometchat-uid-6_user_cometchat-uid-7" + } +} +``` + + ## Receive Delivery & Read Receipts *In other words, as a recipient, how do I know when a message I sent has been delivered or read by someone?* @@ -510,7 +641,7 @@ CometChat.markMessageAsUnread(message).then( 4. `onMessagesReadByAll()` - This event is triggered when a group message is read by all members of the group. This event is only for Group conversations. - + ```javascript let listenerId = "UNIQUE_LISTENER_ID"; @@ -570,6 +701,108 @@ CometChat.addMessageListener( + +**On Event** — `onMessagesDelivered` returns a `MessageReceipt` object for user conversations: +```json +{ + "receiptType": "delivery", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771853565, + "role": "default", + "status": "online", + "tags": [] + }, + "receiverType": "user", + "receiver": "cometchat-uid-6", + "deliveredAt": 1772005348, + "messageId": "25323", + "timestamp": 1772005348 +} +``` + +**On Event** — `onMessagesRead` returns a `MessageReceipt` object for user conversations: +```json +{ + "receiptType": "read", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771853565, + "role": "default", + "status": "online", + "tags": [] + }, + "receiverType": "user", + "receiver": "cometchat-uid-6", + "readAt": 1772005377, + "messageId": "25323", + "timestamp": 1772005377 +} +``` + +**On Event** — `onMessagesDeliveredToAll` returns a `MessageReceipt` object for group conversations (sender is System): +```json +{ + "receiptType": "deliveredToAll", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "app_system", + "name": "System", + "role": "default", + "status": "offline" + }, + "receiverType": "group", + "receiver": "tg1", + "deliveredAt": 1772005516, + "messageId": "25325", + "timestamp": 1772005516 +} +``` + +**On Event** — `onMessagesReadByAll` returns a `MessageReceipt` object for group conversations (sender is System): +```json +{ + "receiptType": "readByAll", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "app_system", + "name": "System", + "role": "default", + "status": "offline" + }, + "receiverType": "group", + "receiver": "tg1", + "readAt": 1772005546, + "messageId": "25325", + "timestamp": 1772005546 +} +``` + + + +**Listener Cleanup Required** — Always remove your message listener when the component unmounts or the listener is no longer needed to avoid memory leaks and duplicate event handling: + +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + +In React Native, place this in a cleanup function inside `useEffect` or in `componentWillUnmount`. + + You will receive events in the form of `MessageReceipt` objects. The message receipt contains the below parameters: | Parameter | Information | @@ -590,10 +823,13 @@ However, for a group message, if you wish to fetch the `deliveredAt` and `readAt ### Receipt History for a Single Message +{/* Fetch delivery & read receipts for a specific message — CometChat.getMessageReceipts(messageId) + Returns a list of MessageReceipt objects with per-user delivery/read status. */} + To fetch the message receipts, you can use the `getMessageReceipts()` method. - + ```javascript let messageId = msgId; CometChat.getMessageReceipts(messageId).then( @@ -638,3 +874,60 @@ The following features will be available only if the **Enhanced Messaging Status * `markMessageAsUnread` method. + +## Best Practices + + + + Mark messages as **delivered** as soon as they are received by the device — typically when fetching messages or receiving a real-time message while the app is open. Mark messages as **read** only when the user actually views the conversation or message. This distinction gives senders accurate insight into whether their message reached the device versus was actually seen. + + + + Rather than calling `markAsDelivered()` for every individual message, pass the **last message** in a fetched list. The SDK marks all prior messages in that conversation as delivered automatically, reducing unnecessary API calls. + + + + Remove message listeners when a component unmounts using `CometChat.removeMessageListener(listenerId)`. Failing to do so can cause memory leaks, duplicate callbacks, and unexpected behavior — especially in React Native navigation flows where screens may mount and unmount frequently. + + + + Prefer passing the full `BaseMessage` object to `markAsDelivered()` and `markAsRead()` instead of individual parameters. This is simpler, less error-prone, and ensures the SDK has all the context it needs. + + + +## Troubleshooting + + + + Ensure you have registered a `MessageListener` with `CometChat.addMessageListener()` **before** the receipt events are dispatched. Verify the listener ID is unique and that you haven't accidentally removed the listener elsewhere. Also confirm the user is logged in and the WebSocket connection is active. + + + + Check that you are passing valid parameters — `messageId`, `receiverId`, `receiverType`, and `senderId` must all be correct. For group messages, `receiverId` should be the group GUID, not a user UID. Use the `.then()` error callback to inspect the `CometChatException` for details. + + + + These events require the **Enhanced Messaging Status** feature to be enabled for your app in the [CometChat Dashboard](https://app.cometchat.com). Verify this setting is turned on if you rely on group-level delivery and read tracking. + + + + You cannot mark your own messages as unread — this method only works for messages received from other users. Additionally, the `markMessageAsUnread` method requires the **Enhanced Messaging Status** feature to be enabled. + + + +## Next Steps + + + + Learn how to send text, media, and custom messages to users and groups. + + + Set up real-time message listeners and fetch missed messages. + + + Fetch and display the user's conversation list with unread counts. + + + Show real-time typing status in one-on-one and group chats. + + diff --git a/sdk/react-native/direct-call.mdx b/sdk/react-native/direct-call.mdx index 0ddc14e2a..79933e654 100644 --- a/sdk/react-native/direct-call.mdx +++ b/sdk/react-native/direct-call.mdx @@ -1,11 +1,34 @@ --- title: "Call Session" +description: "Start and manage call sessions in your React Native app using the CometChat Calls SDK, including token generation, call settings, listeners, and session control." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference** - Generate token and start a call session: + +```javascript +// Generate call token +const callToken = await CometChatCalls.generateToken(sessionId, userAuthToken); + +// Configure and render +const callSettings = new CometChatCalls.CallSettingsBuilder() + .enableDefaultLayout(true) + .setIsAudioOnlyCall(false) + .build(); + +// +``` + + ## Overview This section demonstrates how to start a call session in a React Native application. Previously known as **Direct Calling**. + +**Available via:** SDK | UI Kits + + Before you begin, we strongly recommend you read the [calling setup guide](/sdk/react-native/calling-setup). @@ -89,6 +112,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ }, onCallEnded: () => { console.log("Call ended"); + // Clear Active Call and End Session - see End Call Session section }, onCallEndButtonPressed: () => { console.log("End call button pressed"); @@ -141,6 +165,7 @@ const callListener = new CometChatCalls.OngoingCallListener({ }, onCallEnded: () => { console.log("Call ended"); + // Clear Active Call and End Session - see End Call Session section }, onCallEndButtonPressed: () => { console.log("End call button pressed"); @@ -186,6 +211,7 @@ return ( | `callToken` | The `GenerateToken` object received from `generateToken()` onSuccess | | `callSettings` | Object of `CallSettings` class configured via `CallSettingsBuilder` | + ### Call Settings Configure the call experience using the following `CallSettingsBuilder` methods: @@ -317,6 +343,11 @@ useEffect(() => { + +Always remove call event listeners when the component unmounts using `CometChatCalls.removeCallEventListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. + + + ### Events | Event | Description | @@ -455,6 +486,7 @@ onCallEndButtonPressed: () => { + ## Methods These methods are available for performing custom actions during an active call session. Use them to build custom UI controls or implement specific behaviors based on your use case. @@ -637,3 +669,63 @@ CometChatCalls.endSession(); + + +## Best Practices + + + + Call tokens are session-specific and time-limited. Generate them right before starting the call session rather than caching them for extended periods. This ensures the token is fresh and reduces the chance of token expiry errors. + + + When using the Ringing flow, remember to call both `CometChat.endCall()` and `CometChatCalls.endSession()`. Missing either call can leave the session in an inconsistent state — the Chat SDK may still show the call as active, or media resources may not be released properly. + + + Always remove call event listeners in your component's cleanup function (e.g., the return function of `useEffect`). Orphaned listeners can cause memory leaks, duplicate event handling, and unexpected behavior when navigating between screens. + + + The `CometChatCalls.Component` should be rendered inside a `View` with `height: '100%'`, `width: '100%'`, and `position: 'relative'`. This ensures the call UI fills the screen correctly and overlays render in the right position. + + + When registering call event listeners with `addCallEventListener`, use a unique `listenerId` per component instance. This prevents one component from accidentally overwriting another component's listener, especially in navigation stacks where multiple screens may be mounted simultaneously. + + + +## Troubleshooting + + + + Ensure the user is logged in and the auth token is valid. Call `CometChat.getLoggedinUser()` to verify the user session is active. If the auth token has expired, re-authenticate the user before generating a call token. + + + Verify that the `CometChatCalls.Component` is wrapped in a `View` with explicit dimensions (`height: '100%'`, `width: '100%'`). The component requires a sized container to render. Also confirm that both `callSettings` and `callToken` props are provided and not `null` or `undefined`. + + + Check that the listener is registered before the call session starts. If using `addCallEventListener`, ensure the `listenerId` is unique and hasn't been overwritten by another registration. Also verify that the Calls SDK has been initialized via `CometChatCalls.init()`. + + + The `onCallEnded` callback only fires for 1:1 calls (exactly 2 participants). For group calls, use `onUserLeft` and `onUserListUpdated` to track when participants leave, and handle session cleanup based on your app's logic. + + + Check device permissions for camera and microphone. On React Native, you need to request `CAMERA` and `RECORD_AUDIO` permissions on Android, and add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `Info.plist` on iOS. Also verify that `setIsAudioOnlyCall` matches your intended call type. + + + +--- + +## Next Steps + + + + Implement a complete calling experience with incoming and outgoing call UI + + + Record call sessions for playback and compliance + + + Customize the main video container and participant tiles + + + Enable screen sharing and presenter layouts in calls + + \ No newline at end of file diff --git a/sdk/react-native/edit-message.mdx b/sdk/react-native/edit-message.mdx index b81b7aa21..57926da7d 100644 --- a/sdk/react-native/edit-message.mdx +++ b/sdk/react-native/edit-message.mdx @@ -1,67 +1,83 @@ --- title: "Edit A Message" +description: "Edit text and custom messages, listen for real-time edit events, and retrieve missed edits using the CometChat React Native SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference** - Edit a text message: +```javascript +let receiverID = "RECEIVER_UID"; +let messageText = "Updated message text"; +let receiverType = CometChat.RECEIVER_TYPE.USER; +let textMessage = new CometChat.TextMessage(receiverID, messageText, receiverType); +textMessage.setId(MESSAGE_ID); + +CometChat.editMessage(textMessage).then( + message => console.log("Message Edited", message), + error => console.log("Edit failed:", error) +); +``` + + + +**Available via:** [SDK](/sdk/react-native/edit-message) | [REST API](/rest-api/messages/update-message) | [UI Kits](/ui-kits/react-native/overview) + While [editing a message](/sdk/react-native/edit-message#edit-a-message) is straightforward, receiving events for edited messages with CometChat has two parts: -1. Adding a listener to receive [real-time message edits](/sdk/react-native/edit-message#real-time-message-edit-events) when your app is running -2. Calling a method to retrieve [missed message edits](/sdk/react-native/edit-message#missed-message-edit-events) when your app was not running +1. Adding a listener to receive [real-time message edits](/sdk/react-native/edit-message#real-time-message-edit-events) when your app is running. +2. Calling a method to retrieve [missed message edits](/sdk/react-native/edit-message#missed-message-edit-events) when your app was not running. ## Edit a Message *In other words, as a sender, how do I edit a message?* -In order to edit a message, you can use the `editMessage()` method. This method takes an object of the `BaseMessage` class. At the moment, you are only allowed to edit `TextMessage` and `CustomMessage`. Thus, the `BaseMessage` object must either be a Text or a Custom Message. +To edit a message, you can use the `editMessage()` method. This method takes an object of the `BaseMessage` class. At the moment, you are only allowed to edit `TextMessage` and `CustomMessage`. Thus, the `BaseMessage` object must either be a Text or a Custom Message. ### Add/Update Tags -While editing a message, you can update the tags associated with the Message. You can use the `setTags()` method to do so. The tags added while editing a message will replace the tags set when the message was sent. +While editing a message, you can update the tags associated with the message. Use the `setTags()` method to do so. The tags added while editing a message will replace the tags set when the message was sent. - + ```javascript let tags = ["pinnedMessage"]; textMessage.setTags(tags); ``` - - + ```javascript let tags = ["pinnedMessage"]; customMessage.setTags(tags); ``` - - + ```typescript let tags: Array = ["pinnedMessage"]; textMessage.setTags(tags); ``` - - + ```typescript let tags: Array = ["pinnedMessage"]; customMessage.setTags(tags); ``` - - Once the message object is ready, you can use the `editMessage()` method and pass the message object to it. - + ```javascript let receiverID = "RECEIVER_UID"; let messageText = "Hello world!"; @@ -79,7 +95,6 @@ message => { } ); ``` - @@ -100,9 +115,7 @@ CometChat.editMessage(textMessage).then( } ); ``` - - The object of the edited message will be returned in the `onSuccess()` callback method of the listener. The message object will contain the `editedAt` field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The `editedBy` field is also set to the UID of the user who edited the message. @@ -120,10 +133,10 @@ By default, CometChat allows certain roles to edit a message. *In other words, as a recipient, how do I know when someone has edited their message when my app is running?* -In order to receive real-time events for message being edited, you need to override the `onMessageEdited()` method of the `MessageListener` class. +To receive real-time events for a message being edited, you need to override the `onMessageEdited()` method of the `MessageListener` class. - + ```javascript var listenerID = "UNIQUE_LISTENER_ID"; @@ -136,7 +149,6 @@ new CometChat.MessageListener({ }) ); ``` - @@ -152,18 +164,20 @@ new CometChat.MessageListener({ }) ); ``` - - + +Always remove your message listeners when the component unmounts to prevent memory leaks and unexpected behavior. Call `CometChat.removeMessageListener("UNIQUE_LISTENER_ID")` in your cleanup function (e.g., in a `useEffect` return or `componentWillUnmount`). + + ## Missed Message Edit Events *In other words, as a recipient, how do I know when someone edited their message when my app was not running?* -When you retrieve the list of previous messages, for the message that was edited, the `editedAt` and the `editedBy` fields will be set. Also, for example, of the total number of messages for a conversation are 100, and the message with message ID 50 was edited. Now the message with id 50 will have the `editedAt` and the `editedBy` fields set whenever it is pulled from the history. Also, the 101st message will be and \[Action] message informing you that the message with id 50 has been edited. +When you retrieve the list of previous messages, for the message that was edited, the `editedAt` and the `editedBy` fields will be set. Also, for example, if the total number of messages for a conversation is 100, and the message with message ID 50 was edited, the message with ID 50 will have the `editedAt` and the `editedBy` fields set whenever it is pulled from the history. Additionally, the 101st message will be an [Action] message informing you that the message with ID 50 has been edited. -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- +For the message edited event, in the `Action` object received, the following fields can help you get the relevant information: 1. `action` - `edited` 2. `actionOn` - Updated message object with the edited details. @@ -171,7 +185,38 @@ For the message edited event, in the `Action` object received, the following fie 4. `actionFor` - User/group object having the details of the receiver to which the message was sent. - -In order to edit a message, you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. - +To edit a message, you need to be either the sender of the message or the admin/moderator of the group in which the message was sent. + + + +- Always verify the message type (`TextMessage` or `CustomMessage`) before attempting an edit, as other message types are not supported. +- Use the `editedAt` and `editedBy` fields to display edit indicators in your UI so users know a message has been modified. +- Register your message edit listener early in the component lifecycle to avoid missing real-time edit events. +- When updating tags via `setTags()`, remember that the new tags fully replace any previously set tags — merge existing tags manually if you need to preserve them. + + + +- **Edit fails with permission error**: Ensure the current user is the message sender, or a group owner/moderator for group messages. +- **`onMessageEdited` not firing**: Confirm that `CometChat.addMessageListener()` has been called with a unique listener ID and that the listener has not been removed prematurely. +- **Edited message not reflected in history**: After editing, re-fetch or update the local message list. The `editedAt` field on the message object confirms the edit was applied. +- **Tags not updating**: Make sure you call `setTags()` on the message object before passing it to `editMessage()`. Tags set during editing replace all previous tags. + + + +## Next Steps + + + + Remove messages from conversations for users or groups. + + + Send text, media, and custom messages to users and groups. + + + Listen for incoming messages in real time and fetch missed messages. + + + Send and receive replies within message threads. + + diff --git a/sdk/react-native/expo-integration-guide.mdx b/sdk/react-native/expo-integration-guide.mdx index 7136d7955..ed0a8b85f 100644 --- a/sdk/react-native/expo-integration-guide.mdx +++ b/sdk/react-native/expo-integration-guide.mdx @@ -1,8 +1,23 @@ --- title: "Expo Integration" +description: "Configure CometChat Calls SDK in an Expo React Native app — add dependencies, set Android and iOS permissions, and use development builds instead of Expo GO." --- + +**Quick Reference** - Key Expo setup steps: +```json +// Android: app.json → android block +"permissions": ["CAMERA", "RECORD_AUDIO", "INTERNET", "MODIFY_AUDIO_SETTINGS"], +"plugins": [["expo-build-properties", { "android": { "minSdkVersion": 24 } }]] + +// iOS: app.json → ios block +"infoPlist": { + "NSCameraUsageDescription": "This app uses the camera for video calls.", + "NSMicrophoneUsageDescription": "This app uses the microphone for audio/video calls." +} +``` + ## Add the CometChatCalls Dependency @@ -16,6 +31,10 @@ To add CometChat Calls SDK, please refer to the steps mentioned [here](/sdk/reac Our React Native Calls SDK does not work with Expo GO since it requires some custom native modules. Also, expo does not recommend using Expo GO for building production grade apps. So in order to use our Calls SDK in an expo app you need to use [development builds](https://docs.expo.dev/develop/development-builds/introduction/). You can follow the official Expo [guide](https://docs.expo.dev/guides/local-app-development/) for more details. + +Expo GO is not supported. You must use [development builds](https://docs.expo.dev/develop/development-builds/introduction/) to use the CometChat Calls SDK in an Expo app. + + ### Android You need to add the below `permissions` & `plugin` block inside `android` block of the `app.json` file. You need to install `expo-build-properties` package in your app. @@ -74,3 +93,36 @@ You need to add the below `permissions` block inside `ios` block of the `app.jso To initialize CometChat Calls SDK, please refer to the guide [here](/sdk/react-native/calling-setup#initialize-cometchatcalls) + +## Troubleshooting + + + + Ensure you're using a development build, not Expo GO. Run `npx expo prebuild` followed by `npx expo run:android` or `npx expo run:ios` to create a development build with native modules. + + + Verify that `minSdkVersion` is set to at least `24` in the `expo-build-properties` plugin config. The CometChat Calls SDK requires Android API level 24 or higher. + + + Check that `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` are set in the `infoPlist` block of your `app.json`. Without these, iOS will silently deny access to camera and microphone. + + + +--- + +## Next Steps + + + + Complete Calls SDK installation and initialization guide + + + Start and manage call sessions after setup is complete + + + Implement incoming and outgoing call UI with ringing + + + Set up the core CometChat Chat SDK for React Native + + \ No newline at end of file diff --git a/sdk/react-native/flag-message.mdx b/sdk/react-native/flag-message.mdx index 350149f5d..edcac842f 100644 --- a/sdk/react-native/flag-message.mdx +++ b/sdk/react-native/flag-message.mdx @@ -1,11 +1,32 @@ --- title: "Flag Message" +description: "Flag and report inappropriate messages for moderation review using the CometChat React Native SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** + +```javascript +// Get available flag reasons +const reasons = await CometChat.getFlagReasons(); + +// Flag a message with a reason +const payload = { reasonId: "spam", remark: "Promotional content" }; +await CometChat.flagMessage("MESSAGE_ID", payload); +``` + +**Required:** Moderation enabled in [Dashboard](https://app.cometchat.com) → Moderation → Advanced Settings + + ## Overview Flagging messages allows users to report inappropriate content to moderators or administrators. When a message is flagged, it appears in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Flagged Messages** for review. + +**Available via:** [SDK](/sdk/react-native/flag-message) | [REST API](/rest-api/moderation/flag-a-message) | [UI Kits](/ui-kit/react-native/core-features#report-message) + + For a complete understanding of how flagged messages are reviewed and managed, see the [Flagged Messages](/moderation/flagged-messages) documentation. @@ -74,20 +95,37 @@ Before flagging a message, retrieve the list of available flag reasons configure -### Response - -The response is an array of flag reason objects: - -```javascript + +**On Success** — `getFlagReasons()` returns an array of flag reason objects: +```json [ - { "id": "spam", "reason": "Spam or misleading" }, - { "id": "harassment", "reason": "Harassment or bullying" }, - { "id": "hate_speech", "reason": "Hate speech" }, - { "id": "violence", "reason": "Violence or dangerous content" }, - { "id": "inappropriate", "reason": "Inappropriate content" }, - { "id": "other", "reason": "Other" } + { + "id": "spam", + "name": "Spam", + "description": "Repeated, promotional, or irrelevant content", + "createdAt": 1761627675, + "updatedAt": 1761627675, + "default": false + }, + { + "id": "sexual", + "name": "Sexual Content", + "description": "Explicit or inappropriate content", + "createdAt": 1761627675, + "updatedAt": 1761627675, + "default": false + }, + { + "id": "harassment", + "name": "Harassment / Bullying", + "description": "Insulting or threatening behavior", + "createdAt": 1761627675, + "updatedAt": 1761627675, + "default": false + } ] ``` + ## Flag a Message @@ -132,6 +170,16 @@ To flag a message, use the `flagMessage()` method with the message ID and a payl + +**On Success** — `flagMessage()` returns a success response: +```json +{ + "success": true, + "message": "Message 25300 has been flagged successfully." +} +``` + + ### Parameters | Parameter | Type | Required | Description | @@ -140,15 +188,6 @@ To flag a message, use the `flagMessage()` method with the message ID and a payl | payload.reasonId | string | Yes | ID of the flag reason (from `getFlagReasons()`) | | payload.remark | string | No | Additional context or explanation from the user | -### Response - -```javascript -{ - "success": true, - "message": "Message with id {{messageId}} has been flagged successfully" -} -``` - ## Complete Example Here's a complete implementation showing how to build a report message flow: @@ -218,3 +257,39 @@ if (result.success) { showToast("Message reported successfully"); } ``` + + + + + - **Cache flag reasons:** Call `getFlagReasons()` once at app initialization or when the report dialog is first opened, then reuse the cached list. Avoid fetching reasons on every report action. + - **Require a reason:** Always require users to select a reason before submitting a flag. This improves the quality of moderation data and helps moderators prioritize reviews. + - **Provide a remark field:** Allow users to add optional context via the `remark` parameter. Additional details help moderators make faster, more informed decisions. + - **Confirm before submitting:** Show a confirmation dialog before calling `flagMessage()` to prevent accidental reports. + - **Show feedback after flagging:** Display a success message or toast after a message is flagged so the user knows their report was submitted. + + + - **`getFlagReasons()` returns an empty array:** Ensure that flag reasons are configured in the [CometChat Dashboard](https://app.cometchat.com) under **Moderation > Advanced Settings**. Moderation must also be enabled for your app. + - **`flagMessage()` fails with an error:** Verify that the `reasonId` matches one of the IDs returned by `getFlagReasons()`. Also confirm that the `messageId` is valid and belongs to a conversation the logged-in user has access to. + - **Flagged messages not appearing in Dashboard:** Check that moderation is enabled in your Dashboard settings. Flagged messages appear under **Moderation > Flagged Messages**. + - **Permission errors:** The logged-in user must be a participant in the conversation containing the message they want to flag. Users cannot flag messages from conversations they are not part of. + + + +--- + +## Next Steps + + + + Edit sent messages in one-on-one and group conversations + + + Delete messages for yourself or for all participants + + + Listen for incoming messages in real time + + + Track message delivery and read status + + diff --git a/sdk/react-native/group-add-members.mdx b/sdk/react-native/group-add-members.mdx index 98170bf0b..cc23c0984 100644 --- a/sdk/react-native/group-add-members.mdx +++ b/sdk/react-native/group-add-members.mdx @@ -1,8 +1,22 @@ --- title: "Add Members To A Group" +description: "Add members to a group, listen for real-time member added events, and handle missed events using the CometChat React Native SDK." --- + +**Quick Reference** - Add members to a group: +```javascript +const members = [ + new CometChat.GroupMember("UID", CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT), +]; +await CometChat.addMembersToGroup("GUID", members, []); +``` + + + +**Available via:** [SDK](/sdk/react-native/group-add-members) | [REST API](/rest-api/group-members/add-members) + ## Add Members to Group @@ -13,7 +27,7 @@ You can add members to the group using the `addMembersToGroup()` method. This me 3. `bannedMembers` - This is the list of `UID's` that need to be banned from the Group. This can be set to `null` if there are no members to be banned. - + ```javascript let GUID = "GUID"; let UID = "UID"; @@ -72,7 +86,7 @@ To receive real-time events whenever a new member is added to a group, you need `onMemberAddedToGroup()` - This method is triggered when any user is added to the group so that the logged in user is informed of the other members added to the group. - + ```javascript var listenerID = "UNIQUE_LISTENER_ID"; @@ -121,6 +135,10 @@ CometChat.addGroupListener( + +Always remove group listeners when the component unmounts using `CometChat.removeGroupListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## Member Added to Group event in Message History *In other words, as a member of a group, how do I know when someone is added to the group when my app is not running?* @@ -133,3 +151,47 @@ For the group member added event, in the `Action` object received, the following 2. `actionOn` - User object containing the details of the user who was added to the group 3. `actionBy` - User object containing the details of the user who added the member to the group 4. `actionFor` - Group object containing the details of the group to which the member was added + +## Best Practices + + + + The `addMembersToGroup()` response includes per-UID results ("success" or error). Check each result rather than assuming all members were added successfully. + + + The logged-in user must have Admin or Moderator scope to add members. Verify scope before attempting the operation. + + + +## Troubleshooting + + + + Verify the logged-in user has Admin or Moderator scope in the group. Participants cannot add members. + + + Check the per-UID results in the response object. Common causes include invalid UIDs or users that don't exist in your CometChat app. + + + Ensure the group listener is registered before the add event occurs. Also verify the `listenerId` is unique. + + + +--- + +## Next Steps + + + + Fetch group member lists with filtering and pagination + + + Kick, ban, and unban group members + + + Update member roles within a group + + + Join public or password-protected groups + + \ No newline at end of file diff --git a/sdk/react-native/group-change-member-scope.mdx b/sdk/react-native/group-change-member-scope.mdx index 318c0c24c..c0c681a2c 100644 --- a/sdk/react-native/group-change-member-scope.mdx +++ b/sdk/react-native/group-change-member-scope.mdx @@ -1,15 +1,31 @@ --- title: "Change Member Scope" +description: "Learn how to change the scope (role) of a group member using the CometChat React Native SDK, including real-time and missed scope change events." --- + +**Quick Reference** +```javascript +// Change member scope +CometChat.updateGroupMemberScope("GUID", "UID", CometChat.GROUP_MEMBER_SCOPE.ADMIN); + +// Listen for scope changes +CometChat.addGroupListener("listenerId", new CometChat.GroupListener({ + onGroupMemberScopeChanged: (message, changedUser, newScope, oldScope, changedGroup) => {} +})); +``` + + +Available via: [SDK](/sdk/react-native/group-change-member-scope) | [REST API](/rest-api/group-members/change-scope) + ## Change Scope of a Group Member In order to change the scope of a group member, you can use the `changeGroupMemberScope()`. - + ```javascript var GUID = "GUID"; var UID = "UID"; @@ -67,7 +83,7 @@ The default scope of any member is `participant`. Only the **Admin** of the grou In order to receive real-time events for the change member scope event, you will need to override the `onGroupMemberScopeChanged()` method of the `GroupListener` class - + ```javascript var listenerID = "UNIQUE_LISTENER_ID"; @@ -125,6 +141,13 @@ CometChat.addGroupListener( + +Always remove group listeners when the component unmounts to prevent memory leaks. +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Scope Changed Events *In other words, as a member of a group, how do I know when someone's scope is changed when my app is not running?* @@ -139,3 +162,36 @@ For the group member scope changed event, in the `Action` object received, the f 4. `actionFor` - Group object containing the details of the group in which the member scope was changed 5. `oldScope` - The original scope of the member 6. `newScope` - The updated scope of the member + + + +- Only admins can change member scope — validate roles before calling `updateGroupMemberScope()` +- Update your local group member list after a successful scope change to keep the UI in sync +- Handle the `onGroupMemberScopeChanged` listener to reflect scope changes made by other admins in real time +- Consider showing a confirmation dialog before promoting a member to admin, as this grants full group control + + + +- **ERR_NOT_A_MEMBER**: The logged-in user is not a member of the group. Ensure the user has joined the group first. +- **ERR_INSUFFICIENT_PERMISSIONS**: Only group admins can change member scope. Verify the logged-in user's role. +- **Scope change not reflecting**: Make sure you've registered a `GroupListener` and are handling `onGroupMemberScopeChanged`. +- **Missed events not appearing**: Fetch previous messages using `MessagesRequest` — scope change actions appear as `Action` messages in the message history. + + + +## Next Steps + + + +Remove or restrict members from a group + + +Transfer group ownership to another member + + +Fetch the list of members in a group + + +Add new members to a group + + diff --git a/sdk/react-native/group-kick-ban-members.mdx b/sdk/react-native/group-kick-ban-members.mdx index dc2df5d4f..2f56458a6 100644 --- a/sdk/react-native/group-kick-ban-members.mdx +++ b/sdk/react-native/group-kick-ban-members.mdx @@ -1,8 +1,29 @@ --- title: "Kick Member From A Group" +description: "Learn how to kick, ban, and unban group members using the CometChat React Native SDK, including fetching banned member lists and handling real-time events." --- + +**Quick Reference** +```javascript +// Kick a member +CometChat.kickGroupMember("GUID", "UID"); + +// Ban a member +CometChat.banGroupMember("GUID", "UID"); + +// Unban a member +CometChat.unbanGroupMember("GUID", "UID"); + +// Fetch banned members +let request = new CometChat.BannedMembersRequestBuilder("GUID").setLimit(30).build(); +request.fetchNext(); +``` + + +Available via: [SDK](/sdk/react-native/group-kick-ban-members) | REST API: [Kick](/rest-api/group-members/kick), [Ban](/rest-api/banned-users/ban) + There are certain actions that can be performed on the group members: @@ -18,7 +39,7 @@ All the above actions can only be performed by the **Admin** or the **Moderator* The Admin or Moderator of a group can kick a member out of the group using the `kickGroupMember()` method. - + ```javascript var GUID = "GUID"; var UID = "UID"; @@ -68,7 +89,7 @@ The kicked user will be no longer part of the group and can not perform any acti The Admin or Moderator of the group can ban a member from the group using the `banGroupMember()` method. - + ```javascript var GUID = "GUID"; var UID = "UID"; @@ -118,7 +139,7 @@ The banned user will be no longer part of the group and can not perform any acti Only Admin or Moderators of the group can unban a previously banned member from the group using the `unbanGroupMember()` method. - + ```javascript var GUID = "GUID"; var UID = "UID"; @@ -176,7 +197,7 @@ The `GUID` of the group for which the banned members are to be fetched must be s This method sets the limit i.e. the number of banned members that should be fetched in a single iteration. - + ```javascript let GUID = "GUID"; let limit = 30; @@ -204,7 +225,7 @@ let bannedGroupMembersRequest: CometChat.BannedMembersRequest = This method allows you to set the search string based on which the banned group members are to be fetched. - + ```javascript let GUID = "GUID"; let limit = 30; @@ -238,7 +259,7 @@ Finally, once all the parameters are set to the builder class, you need to call Once you have the object of the `BannedGroupMembersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `GroupMember` objects containing n number of banned members where n is the limit set in the builder class. - + ```javascript let GUID = "GUID"; let limit = 30; @@ -302,7 +323,7 @@ In order to get real-time events for the kick/ban/unban group members you need t 3. `onGroupMemberUnbanned()` - triggered when any group member has been unbanned. - + ```javascript let listenerID = "UNIQUE_LISTENER_ID"; @@ -378,6 +399,13 @@ CometChat.addGroupListener( + +Always remove group listeners when the component unmounts to prevent memory leaks. +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + ## Missed Group Member Kicked/Banned Events *In other words, as a member of a group, how do I know when someone is banned/kicked when my app is not running?* @@ -404,3 +432,39 @@ For group member unbanned event, the details can be obtained using the below fie 2. `actionBy` - User object containing the details of the user who has unbanned the member 3. `actionOn` - User object containing the details of the member that has been unbanned 4. `actionFor` - Group object containing the details of the Group from which the member was unbanned + + + + +- Always confirm with the user before kicking or banning — these are disruptive actions +- Use ban for persistent rule violations and kick for temporary removals (kicked users can rejoin) +- Keep your local member list in sync by handling `onGroupMemberKicked`, `onGroupMemberBanned`, and `onGroupMemberUnbanned` listeners +- When fetching banned members, use pagination (`fetchNext()`) to handle large lists efficiently +- Only admins and moderators can perform these actions — check the logged-in user's scope before showing kick/ban UI controls + + + +- **ERR_NOT_A_MEMBER**: The logged-in user is not a member of the group. Ensure the user has joined the group first. +- **ERR_INSUFFICIENT_PERMISSIONS**: Only admins or moderators can kick/ban members. Verify the logged-in user's role. +- **Banned user can still rejoin**: Make sure you used `banGroupMember()` and not `kickGroupMember()` — kicked users can rejoin, banned users cannot. +- **Unban not working**: Only admins or moderators can unban. Also ensure the user was actually banned (not just kicked). +- **Listener events not firing**: Confirm you registered a `GroupListener` with the correct listener ID and are handling the right callback methods. + + + +## Next Steps + + + +Promote or demote group members + + +Transfer group ownership to another member + + +Fetch the list of members in a group + + +Add new members to a group + + diff --git a/sdk/react-native/groups-overview.mdx b/sdk/react-native/groups-overview.mdx index 4f3d1c363..119e4be1e 100644 --- a/sdk/react-native/groups-overview.mdx +++ b/sdk/react-native/groups-overview.mdx @@ -1,10 +1,30 @@ --- title: "Groups" sidebarTitle: "Overview" +description: "Overview of group functionality in CometChat React Native SDK — create, manage, and interact with public, private, and password-protected groups." --- - +## Overview Groups help your users to converse together in a single space. You can have three types of groups- private, public and password protected. Each group includes three kinds of users- owner, moderator, member. + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Fetch group lists, search groups, and get group details + + + Join public or password-protected groups + + + Manage members, roles, and permissions within groups + + \ No newline at end of file diff --git a/sdk/react-native/interactive-messages.mdx b/sdk/react-native/interactive-messages.mdx index 8498fb652..8dcd576bd 100644 --- a/sdk/react-native/interactive-messages.mdx +++ b/sdk/react-native/interactive-messages.mdx @@ -1,14 +1,35 @@ --- title: "Interactive Messages" +description: "Send and receive interactive messages with embedded forms, cards, and custom interactive elements using the CometChat React Native SDK." --- + +**Quick Reference** - Send an interactive message and listen for it: +```javascript +// Send an interactive message +const interactiveMessage = new CometChat.InteractiveMessage( + "UID", CometChat.RECEIVER_TYPE.USER, "form", { title: "Survey", formFields: [] } +); +await CometChat.sendInteractiveMessage(interactiveMessage); + +// Listen for incoming interactive messages +CometChat.addMessageListener("interactive-listener", new CometChat.MessageListener({ + onInteractiveMessageReceived: (msg) => console.log("Interactive:", msg), + onInteractionGoalCompleted: (msg) => console.log("Goal completed:", msg), +})); +``` + + + +**Available via:** [SDK](/sdk/react-native/interactive-messages) | [REST API](/rest-api/chat-apis) + An `InteractiveMessage` is a specialized object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input. ## InteractiveMessage -`InteractiveMessage` is a chat message with embedded interactive content. It can contain various properties: +`InteractiveMessage` is a chat message with embedded interactive content. It can contain the following properties: | Parameter | Description | | | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------- | @@ -28,27 +49,43 @@ An `Interaction` represents a user action involved with an `InteractiveMessage`. ## Mark as Interacted -This method marks a message as interacted by identifying it with the provided Id. it also logs the interactive element associated with the interaction. +This method marks a message as interacted by identifying it with the provided Id. It also logs the interactive element associated with the interaction. - -```javascript -CometChat.markAsInteracted(message?.getId(), elementId) -.then((response) => { - console.log("Mark As Interacted", response); - }); - .catch((error) => { - console.log("error while markAsInteracted", error); - }); -``` - - - + + ```javascript + CometChat.markAsInteracted(message?.getId(), elementId) + .then((response) => { + console.log("Mark As Interacted", response); + }) + .catch((error) => { + console.log("error while markAsInteracted", error); + }); + ``` + + + ```typescript + CometChat.markAsInteracted(message?.getId(), elementId) + .then((response) => { + console.log("Mark As Interacted", response); + }) + .catch((error) => { + console.log("error while markAsInteracted", error); + }); + ``` + + +**On Success** — `markAsInteracted()` returns a success message: +```json +"The message id 25308 has been marked as interacted for the user cometchat-uid-7." +``` + + ## Goal Completion -A key feature of InteractiveMessage is checking whether a user's interactions with the message meet the defined `InteractionGoal` +A key feature of `InteractiveMessage` is checking whether a user's interactions with the message meet the defined `InteractionGoal`. You would be tracking every interaction users perform on an `InteractiveMessage` (captured as `Interaction` objects) and comparing those with the defined `InteractionGoal`. The completion of a goal can vary depending on the goal type: @@ -73,21 +110,146 @@ The `InteractiveMessage` can be sent using the `sendInteractiveMessage` method o Here is an example of how to use it: - -```typescript -CometChat.sendInteractiveMessage(message) -.then((message: CometChat.InteractiveMessage) => { - console.log("message sent successfully", message.getSentAt()); -}) -.catch((error: CometChat.CometChatException) => { - console.log("error while sending message", { error }); -}); -``` - - - + + ```javascript + CometChat.sendInteractiveMessage(message) + .then((message) => { + console.log("message sent successfully", message.getSentAt()); + }) + .catch((error) => { + console.log("error while sending message", { error }); + }); + ``` + + + ```typescript + CometChat.sendInteractiveMessage(message) + .then((message: CometChat.InteractiveMessage) => { + console.log("message sent successfully", message.getSentAt()); + }) + .catch((error: CometChat.CometChatException) => { + console.log("error while sending message", { error }); + }); + ``` + + +**On Success** — `sendInteractiveMessage()` returns the sent interactive message object: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "form", + "receiverType": "user", + "category": "interactive", + "interactiveData": { + "title": "Quick Survey", + "formFields": [ + { + "elementType": "textInput", + "elementId": "field1", + "label": "How was your experience?", + "optional": false + } + ], + "submitElement": { + "elementType": "button", + "elementId": "submit_btn", + "buttonText": "Submit" + }, + "interactableElementIds": ["submit_btn"] + }, + "interactionGoal": { + "elementIds": [], + "type": "anyAction" + }, + "data": { + "interactiveData": { + "title": "Quick Survey", + "formFields": [ + { + "elementType": "textInput", + "elementId": "field1", + "label": "How was your experience?", + "optional": false + } + ], + "submitElement": { + "elementType": "button", + "elementId": "submit_btn", + "buttonText": "Submit" + }, + "interactableElementIds": ["submit_btn"] + }, + "interactionGoal": { + "elementIds": [], + "type": "anyAction" + }, + "resource": "REACT_NATIVE-4_0_14-8dc16e6c-8c88-44f2-88b8-629ad14ccadb-1771998690866", + "allowSenderInteraction": false, + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771998694, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771998700, + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "tags": [] + }, + "entityType": "user" + } + } + }, + "id": "25308", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771998694, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771998700, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771998776, + "updatedAt": 1771998776 +} +``` + + ## Event Listeners CometChat SDK provides event listeners to handle real-time events related to `InteractiveMessage`. @@ -99,22 +261,148 @@ The `onInteractiveMessageReceived` event listener is triggered when an `Interact Here is an example: - -```typescript -CometChat.addMessageListener( -"UNIQUE_LISTENER_ID", -new CometChat.MessageListener({ - onInteractiveMessageReceived: message => { - console.log("on Interactive Message Received", message); - } -}) -); -``` - - - + + ```javascript + CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractiveMessageReceived: (message) => { + console.log("on Interactive Message Received", message); + } + }) + ); + ``` + + + ```typescript + CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractiveMessageReceived: (message: CometChat.InteractiveMessage) => { + console.log("on Interactive Message Received", message); + } + }) + ); + ``` + + +**On Event** — `onInteractiveMessageReceived` returns the received interactive message object: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "form", + "receiverType": "user", + "category": "interactive", + "interactiveData": { + "title": "Quick Survey", + "formFields": [ + { + "elementType": "textInput", + "elementId": "field1", + "label": "How was your experience?", + "optional": false + } + ], + "submitElement": { + "elementType": "button", + "elementId": "submit_btn", + "buttonText": "Submit" + }, + "interactableElementIds": ["submit_btn"] + }, + "interactionGoal": { + "elementIds": [], + "type": "anyAction" + }, + "data": { + "interactiveData": { + "title": "Quick Survey", + "formFields": [ + { + "elementType": "textInput", + "elementId": "field1", + "label": "How was your experience?", + "optional": false + } + ], + "submitElement": { + "elementType": "button", + "elementId": "submit_btn", + "buttonText": "Submit" + }, + "interactableElementIds": ["submit_btn"] + }, + "interactionGoal": { + "elementIds": [], + "type": "anyAction" + }, + "resource": "REACT_NATIVE-4_0_14-8dc16e6c-8c88-44f2-88b8-629ad14ccadb-1771998690866", + "allowSenderInteraction": false, + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771998694, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771998700, + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "tags": [] + }, + "entityType": "user" + } + } + }, + "id": "25308", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771998694, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771998700, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771998776, + "updatedAt": 1771998776 +} +``` + + ### On Interaction Goal Completed The `onInteractionGoalCompleted` event listener is invoked when an interaction goal is achieved. @@ -122,24 +410,76 @@ The `onInteractionGoalCompleted` event listener is invoked when an interaction g Here is an example: - -```typescript -CometChat.addMessageListener( -"UNIQUE_LISTENER_ID", -new CometChat.MessageListener({ - onInteractionGoalCompleted: message => { - console.log("on Interaction Goal Completed", message); - } -}) -); -``` - - - + + ```javascript + CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractionGoalCompleted: (message) => { + console.log("on Interaction Goal Completed", message); + } + }) + ); + ``` + + + ```typescript + CometChat.addMessageListener( + "UNIQUE_LISTENER_ID", + new CometChat.MessageListener({ + onInteractionGoalCompleted: (message: CometChat.InteractiveMessage) => { + console.log("on Interaction Goal Completed", message); + } + }) + ); + ``` + These event listeners offer your application a way to provide real-time updates in response to incoming interactive messages and goal completions, contributing to a more dynamic and responsive user chat experience. + +**Listener Cleanup:** Always remove message listeners when they are no longer needed. Remove the listener in `componentWillUnmount()` or the cleanup function of a `useEffect` hook to prevent memory leaks. + +```javascript +CometChat.removeMessageListener("UNIQUE_LISTENER_ID"); +``` + + ## Usage An `InteractiveMessage` is constructed with the receiver's UID, the receiver type, the interactive type, and interactive data as a JSONObject. Once created, the `InteractiveMessage` can be sent using CometChat's `sendInteractiveMessage()` method. Incoming `InteractiveMessages` can be received and processed via CometChat's message listener framework. + + + + - Use descriptive, unique listener IDs (e.g., `"interactive-form-listener"`) to avoid conflicts with other listeners + - Always remove message listeners on component unmount to prevent memory leaks + - Set `allowSenderInteraction` to `true` only when the sender needs to interact with their own message (e.g., previewing a form) + - Define clear `InteractionGoal` types to accurately track user engagement with interactive elements + - Handle both `onInteractiveMessageReceived` and `onInteractionGoalCompleted` events to provide a complete interactive experience + + + - **Interactive message not sending:** Verify that `interactiveData` is a valid JSON object and all required fields (`receiverId`, `receiverType`, `messageType`) are set + - **Not receiving interactive messages:** Ensure the message listener is registered with `onInteractiveMessageReceived` and the user is logged in + - **Goal not completing:** Check that the `InteractionGoal` type matches the expected interactions — use `ANY_ACTION` for simple cases and `ALL_OF` only when every specified element must be interacted with + - **`markAsInteracted` failing:** Confirm that the message ID and element ID are valid and that the user has permission to interact with the message + - **Duplicate events:** Verify you are not registering the same listener ID multiple times without removing the previous one + + + +## Next Steps + + + + Send text, media, custom, and interactive messages to users and groups + + + Listen for real-time messages and fetch missed or unread messages + + + Understand message categories, types, and hierarchy including interactive messages + + + Explore the full range of CometChat messaging capabilities + + diff --git a/sdk/react-native/join-group.mdx b/sdk/react-native/join-group.mdx index d0a4fa701..843c478d8 100644 --- a/sdk/react-native/join-group.mdx +++ b/sdk/react-native/join-group.mdx @@ -1,15 +1,30 @@ --- title: "Join A Group" +description: "Join public or password-protected groups, listen for real-time join events, and handle missed join events using the CometChat React Native SDK." --- + +**Quick Reference** - Join a group: +```javascript +// Join a public group +await CometChat.joinGroup("GUID", CometChat.GROUP_TYPE.PUBLIC, ""); + +// Join a password-protected group +await CometChat.joinGroup("GUID", CometChat.GROUP_TYPE.PASSWORD, "password123"); +``` + + + +**Available via:** [SDK](/sdk/react-native/join-group) | [REST API](/rest-api/group-members/add-members) + ## Join a Group In order to start participating in group conversations, you will have to join a group. You can do so using the `joinGroup()` method. - + ```javascript var GUID = "GUID"; var password = ""; @@ -64,7 +79,7 @@ You can identify if a group is joined using the `hasJoined` parameter in the `Gr If a user joins any group, the members of the group receive a real-time event in the `onGroupMemberJoined()` method of the `GroupListener` class. - + ```javascript CometChat.addGroupListener( "UNIQUE_LISTNER_ID", @@ -94,6 +109,10 @@ CometChat.addGroupListener( + +Always remove group listeners when the component unmounts using `CometChat.removeGroupListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## Missed Group Member Joined Events *In other words, as a member of a group, how do I know if someone joins the group when my app is not running?* @@ -105,3 +124,47 @@ For the group member joined event, in the `Action` object received, the followin 1. `action` - `joined` 2. `actionBy` - User object containing the details of the user who joined the group 3. `actionFor`- Group object containing the details of the group the user has joined + +## Best Practices + + + + Before calling `joinGroup()`, check the `hasJoined` property on the `Group` object. If the user has already joined, calling `joinGroup()` again will return an error. + + + For password-protected groups, prompt the user for the password before calling `joinGroup()`. Pass the password as the third parameter. + + + +## Troubleshooting + + + + Private groups cannot be joined directly. Members must be added by an admin or owner using the group members API. Only public and password-protected groups support `joinGroup()`. + + + Ensure the password string matches exactly. Passwords are case-sensitive. If the user enters an incorrect password, the SDK returns an error. + + + Verify the group listener is registered with `addGroupListener()` before the join event occurs. Also ensure the `listenerId` is unique and hasn't been overwritten. + + + +--- + +## Next Steps + + + + Leave groups and stop receiving updates + + + Manage members, roles, and permissions within groups + + + Send text, media, and custom messages to groups + + + Fetch group lists and group details + + \ No newline at end of file diff --git a/sdk/react-native/key-concepts.mdx b/sdk/react-native/key-concepts.mdx index 023f77247..458c45e21 100644 --- a/sdk/react-native/key-concepts.mdx +++ b/sdk/react-native/key-concepts.mdx @@ -1,92 +1,111 @@ --- title: "Key Concepts" +description: "Understand the fundamental building blocks of CometChat — users, groups, messaging categories, authentication, and roles." --- + +**Quick Reference** - Core identifiers you'll use throughout the SDK: +```javascript +// User identified by UID +const user = new CometChat.User("user1"); +user.setName("Kevin"); -### CometChat Dashboard +// Group identified by GUID +const group = new CometChat.Group("group1", "My Group", CometChat.GROUP_TYPE.PUBLIC); + +// Message categories: message | custom | action | call | interactive +``` + + +## CometChat Dashboard The CometChat Dashboard enables you to create new apps (projects) and manage your existing apps. -How many apps to create? +**How many apps to create?** -Ideally, you should create two apps- one for development and one for production. And you should use a single app irrespective of the number of platforms. > > Do not create separate apps for every platform; if you do, your users on different platforms will not be able to communicate with each other! +Ideally, you should create two apps — one for development and one for production. You should use a single app irrespective of the number of platforms. +Do not create separate apps for every platform; if you do, your users on different platforms will not be able to communicate with each other. -* For every app, a unique App ID is generated. This App ID will be required when integrating CometChat within your app. -* Along with the App ID, you will need to create an Auth Key (from the Dashboard) which can be used for user authentication. +- For every app, a unique App ID is generated. This App ID will be required when integrating CometChat within your app. +- Along with the App ID, you will need to create an Auth Key (from the Dashboard) which can be used for user authentication. -### Auth & Rest API Keys +## Auth & REST API Keys You can generate two types of keys from the dashboard. | Type | Privileges | Recommended Use | | ------------ | ---------------------------------------------------------------- | --------------------------------------------- | -| Auth Key | The Auth Key can be used to create & login users. | In your client side code (during development) | -| Rest API Key | The Rest API Key can be used to perform any CometChat operation. | In your server side code | +| Auth Key | The Auth Key can be used to create & login users. | In your client-side code (during development) | +| REST API Key | The REST API Key can be used to perform any CometChat operation. | In your server-side code | + + +**Security Warning:** Auth Keys should only be used during development. For production environments, use [Auth Tokens](/sdk/react-native/authentication-overview#login-using-auth-token) generated from your server to authenticate users securely. + -### Users +## Users A user is anyone who uses CometChat. ### UID -* Each user is uniquely identified using UID. -* The UID is typically the primary ID of the user from your database. +- Each user is uniquely identified using a UID. +- The UID is typically the primary ID of the user from your database. - UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - ### Auth Token -* A single user can have multiple auth tokens. The auth tokens should be per user per device. -* It should be generated by API call ideally, via server to server call. The auth token should then be given to CometChat for login. -* An Auth Token can only be deleted via dashboard or using REST API. +- A single user can have multiple auth tokens. The auth tokens should be per user per device. +- It should be generated by an API call ideally, via a server-to-server call. The auth token should then be given to CometChat for login. +- An Auth Token can only be deleted via the dashboard or using the REST API. -### Authentication +## Authentication To allow a user to use CometChat, the user must log in to CometChat. -**CometChat does not handle user management.** You must handle user registration and login at your end. Once the user is logged into your app/site, you can log in the user to CometChat **programmatically**. So the user does not ever directly login to CometChat. + +**CometChat does not handle user management.** You must handle user registration and login at your end. Once the user is logged into your app/site, you can log in the user to CometChat **programmatically**. The user does not ever directly login to CometChat. + + **CometChat does not handle friends management.** If you want to associate friends with your users, you must handle friends management in your app. Once two users are friends (i.e. they have accepted each other as friends), then you can associate them as friends in CometChat. + ### Typical Workflow | Your App | Your Server | CometChat | | ----------------------------- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ | -| User registers in your app | You store the user information in your database (e.g. ID, name, email, phone, location etc. in `users` table) | You add the user to CometChat (only ID & name) using the Rest API | +| User registers in your app | You store the user information in your database (e.g. ID, name, email, phone, location etc. in `users` table) | You add the user to CometChat (only ID & name) using the REST API | | User logs in to your app | You verify the credentials, login the user and retrieve the user ID | You log in the user to CometChat using the same user ID programmatically | | User sends a friend request | You display the request to the potential friend | No action required | -| User accepts a friend request | You display the users as friends | You add both the users as friends using the Rest API | +| User accepts a friend request | You display the users as friends | You add both the users as friends using the REST API | -### User Roles +## User Roles A role is a category for a group of similar users. For example, you may want to group your premium users using the role "Premium". You then use this to filter users or enable/disable features by writing conditional code. -### User List +## User List -* The User List can be used to build the **Contacts** or **Who's Online** view in your app. -* The list of users can be different based on the logged-in user. +- The User List can be used to build the **Contacts** or **Who's Online** view in your app. +- The list of users can be different based on the logged-in user. -### Groups +## Groups A group can be used for multiple users to communicate with each other on a particular topic/interest. ### GUID -* Each group is uniquely identified using GUID. -* The GUID is typically the primary ID of the group from your database. If you do not store group information in your database, you can generate a random string for use as GUID. +- Each group is uniquely identified using a GUID. +- The GUID is typically the primary ID of the group from your database. If you do not store group information in your database, you can generate a random string for use as GUID. - GUID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - ### Types @@ -101,7 +120,7 @@ CometChat supports three different types of groups: ### Members -Once a participant joins a group, they become a member of the group. Members are part of the group indefinitely i.e. they will keep receiving messages, calls & notifications. To stop, the participant must either be kicked, banned or intentionally leave the group. +Once a participant joins a group, they become a member of the group. Members are part of the group indefinitely — they will keep receiving messages, calls & notifications. To stop, the participant must either be kicked, banned or intentionally leave the group. CometChat supports three different types of member scopes in a group: @@ -111,15 +130,33 @@ CometChat supports three different types of member scopes in a group: | Moderator | - | - Change scope of moderator or participant. - Update group - Kick & Ban Participants - Send & Receive Messages & Calls | | Participant | Any other user is assigned Participant scope | - Send & Receive Messages & Calls | -### Messaging - -Any message in CometChat can belong to either one of the below categories - -| Category | Description | -| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| message | Any message belonging to the category `message` can belong to either one of the below types: 1. text 2. image 3. video 4. audio 5. file | -| custom | Custom messages are an option available for developers to send custom data across to users/groups. To send any additional data that does not fit in the default categories and types provided by CometChat, you can use the custom messages. | -| action | Action messages are system-generated messages. These can belong to either of the below types:1. groupMember - when the action is performed on a group member 2. message - when the action is performed on a message | -| call | These are call-related messages. These can belong to either one of the two types:1. audio 2. video | - -For more information, you can refer to the [Message structure and hierarchy guide](/sdk/react-native/message-structure-and-hierarchy). +## Messaging + +Any message in CometChat belongs to one of the following categories: + +| Category | Description | +| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| message | Any message belonging to the category `message` can belong to either one of the below types: 1. text 2. image 3. video 4. audio 5. file | +| custom | Custom messages are an option available for developers to send custom data across to users/groups. To send any additional data that does not fit in the default categories and types provided by CometChat, you can use custom messages. | +| action | Action messages are system-generated messages. These can belong to either of the below types: 1. groupMember — when the action is performed on a group member 2. message — when the action is performed on a message | +| call | These are call-related messages. These can belong to either one of the two types: 1. audio 2. video | +| interactive | Interactive messages encapsulate interactive units within a chat message, such as forms or cards. See [Interactive Messages](/sdk/react-native/interactive-messages) | + +For more information, you can refer to the [Message Structure and Hierarchy guide](/sdk/react-native/message-structure-and-hierarchy). + +## Next Steps + + + + Initialize CometChat and authenticate users in your app + + + Start sending text, media, and custom messages + + + Track real-time online/offline status of users + + + Understand message categories, types, and hierarchy + + diff --git a/sdk/react-native/leave-group.mdx b/sdk/react-native/leave-group.mdx index b879d5049..e544a4954 100644 --- a/sdk/react-native/leave-group.mdx +++ b/sdk/react-native/leave-group.mdx @@ -1,15 +1,26 @@ --- title: "Leave A Group" +description: "Leave groups, listen for real-time leave events, and handle missed leave events using the CometChat React Native SDK." --- + +**Quick Reference** - Leave a group: +```javascript +await CometChat.leaveGroup("GUID"); +``` + + + +**Available via:** [SDK](/sdk/react-native/leave-group) | [REST API](/rest-api/group-members/kick) + ## Leave a Group In order to stop receiving updates and messages for any particular joined group, you will have to leave the group using the `leaveGroup()` method. - + ```javascript var GUID = "GUID"; // guid of the group to join @@ -54,7 +65,7 @@ Once a group is left, the user will no longer receive any updates or messages pe If a user leaves any group, The members of the group receive a real-time event in the `onGroupMemberLeft()` method of the `GroupListener` class. - + ```javascript CometChat.addGroupListener( "UNIQUE_LISTENER_ID", @@ -84,6 +95,10 @@ CometChat.addGroupListener( + +Always remove group listeners when the component unmounts using `CometChat.removeGroupListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. + + ## Missed Group Member Left Events *In other words, as a member of a group, how do I know if someone has left it when my app is not running?* @@ -95,3 +110,44 @@ For the group member left event, in the `Action` object received, the following 1. `action` - `left` 2. `actionBy` - User object containing the details of the user who left the group 3. `actionFor` - Group object containing the details of the group the user has left + +## Best Practices + + + + After successfully leaving a group, remove any local references to the group's messages, members, or conversation data. This prevents stale data from appearing in your UI. + + + If the logged-in user is the group owner, consider transferring ownership to another admin or member before leaving. Leaving as the owner may have different behavior depending on your app's configuration. + + + +## Troubleshooting + + + + Verify the GUID is correct and the logged-in user is actually a member of the group. You can check membership using `getGroup()` and the `hasJoined` property. + + + Ensure the `leaveGroup()` call completed successfully (resolved the promise). Also remove any active group listeners for that group to stop receiving real-time events. + + + +--- + +## Next Steps + + + + Join public or password-protected groups + + + Delete groups and handle related cleanup + + + Manage members, roles, and permissions within groups + + + Fetch group lists and group details + + \ No newline at end of file diff --git a/sdk/react-native/login-listener.mdx b/sdk/react-native/login-listener.mdx index eb91e8364..626896499 100644 --- a/sdk/react-native/login-listener.mdx +++ b/sdk/react-native/login-listener.mdx @@ -1,12 +1,25 @@ --- title: "Login Listener" +description: "Receive real-time updates for login and logout events using the LoginListener class in CometChat React Native SDK." --- + +**Quick Reference** - Register a login listener: +```javascript +CometChat.addLoginListener( + "UNIQUE_LISTENER_ID", + new CometChat.LoginListener({ + loginSuccess: (e) => console.log("Logged in", e), + loginFailure: (e) => console.log("Login failed", e), + logoutSuccess: () => console.log("Logged out"), + logoutFailure: (e) => console.log("Logout failed", e), + }) +); +``` + -The CometChat SDK provides you with real-time updates for the `login` and `logout` events. This can be achieved using the `LoginListener` class provided. LoginListener consists of 4 events that can be triggered. These are as follows: - -Login Listener provides you with the below 4 methods: +The CometChat SDK provides you with real-time updates for the `login` and `logout` events. This can be achieved using the `LoginListener` class. LoginListener provides the following 4 methods: | Delegate Method | Information | | -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -15,76 +28,109 @@ Login Listener provides you with the below 4 methods: | logoutSuccess() | Informs you about the user being logged out successfully. | | logoutFailure(event) | Informs you about the failure while logging out the user. The reason for the failure can be obtained from the object of the `CometChatException` class. | -To add the `LoginListener`, you need to use the `addLoginListener()` method provided by the SDK which takes a unique identifier for the listener and of the the `LoginListener` class itself. +## Add Login Listener + +To add the `LoginListener`, use the `addLoginListener()` method provided by the SDK. It takes a unique identifier for the listener and an instance of the `LoginListener` class. - -```javascript -var listenerID = "UNIQUE_LISTENER_ID"; -CometChat.addLoginListener( - listenerID, - new CometChat.LoginListener({ - loginSuccess: (e) => { + + ```javascript + var listenerID = "UNIQUE_LISTENER_ID"; + + CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (e) => { console.log("LoginListener :: loginSuccess", e); - }, - loginFailure: (e) => { + }, + loginFailure: (e) => { console.log("LoginListener :: loginFailure", e); - }, - logoutSuccess: () => { + }, + logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); - }, - logoutFailure: (e) => { + }, + logoutFailure: (e) => { console.log("LoginListener :: logoutFailure", e); - } - }) -); -``` - - - - -```javascript -var listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.addLoginListener( - listenerID, - new CometChat.LoginListener({ - loginSuccess: (user: CometChat.User) => { + }, + }) + ); + ``` + + + ```typescript + var listenerID: string = "UNIQUE_LISTENER_ID"; + + CometChat.addLoginListener( + listenerID, + new CometChat.LoginListener({ + loginSuccess: (user: CometChat.User) => { console.log("LoginListener :: loginSuccess", user); - }, - loginFailure: (error: CometChat.CometChatException) => { + }, + loginFailure: (error: CometChat.CometChatException) => { console.log("LoginListener :: loginFailure", error); - }, - logoutSuccess: () => { + }, + logoutSuccess: () => { console.log("LoginListener :: logoutSuccess"); - }, - logoutFailure: (error: CometChat.CometChatException) => { + }, + logoutFailure: (error: CometChat.CometChatException) => { console.log("LoginListener :: logoutFailure", error); - } - }) -); -``` - - - + }, + }) + ); + ``` + -In order to stop receiving events related to login and logout you need to use the removeLoginListener() method provided by the SDK and pass the ID of the listener that needs to be removed. - - - -```javascript -var listenerID = "UNIQUE_LISTENER_ID"; -CometChat.removeLoginListener(listenerID); -``` - - - - -```javascript -var listenerID: string = "UNIQUE_LISTENER_ID"; -CometChat.removeLoginListener(listenerID); -``` +## Remove Login Listener - +To stop receiving events related to login and logout, use the `removeLoginListener()` method and pass the ID of the listener that needs to be removed. + + + ```javascript + var listenerID = "UNIQUE_LISTENER_ID"; + CometChat.removeLoginListener(listenerID); + ``` + + + ```typescript + var listenerID: string = "UNIQUE_LISTENER_ID"; + CometChat.removeLoginListener(listenerID); + ``` + + + +**Listener Cleanup:** Always remove your login listeners when they are no longer needed (e.g., when a component unmounts) to prevent memory leaks and unexpected behavior. Use `removeLoginListener()` with the same listener ID you used when adding it. + + + + + - Use unique, descriptive listener IDs to avoid conflicts (e.g., `"login-screen-listener"`) + - Add listeners in component mount lifecycle and remove them on unmount + - Handle all four events to provide a complete user experience + - Use `loginFailure` to display user-friendly error messages + + + - **Listener not firing:** Ensure the listener was added before the login/logout event occurs + - **Duplicate events:** Check that you're not adding the same listener multiple times without removing it first + - **Memory leaks:** Verify that `removeLoginListener()` is called when the component unmounts + + + +## Next Steps + + + + Learn about login methods and session management + + + Track real-time online/offline status of users + + + Monitor and manage WebSocket connection status + + + Start sending text, media, and custom messages + + diff --git a/sdk/react-native/managing-web-sockets-connections-manually.mdx b/sdk/react-native/managing-web-sockets-connections-manually.mdx index f79a9de8e..1db29d054 100644 --- a/sdk/react-native/managing-web-sockets-connections-manually.mdx +++ b/sdk/react-native/managing-web-sockets-connections-manually.mdx @@ -1,10 +1,24 @@ --- title: "Managing Web Sockets Connections Manually" +description: "Learn how to manually manage WebSocket connections in the CometChat React Native SDK, including connecting, disconnecting, and maintaining background connections." --- + +**Quick Reference** +```javascript +// Disable auto connection during init +new CometChat.AppSettingsBuilder() + .autoEstablishSocketConnection(false) + .build(); +// Manually connect / disconnect / ping +CometChat.connect(); +CometChat.disconnect(); +CometChat.ping(); +``` + -## Default SDK behaviour on login +## Default SDK Behaviour on Login When the login method of the SDK is called, the SDK performs the below operations: @@ -34,9 +48,7 @@ To enable auto mode, you need to set the autoEstablishSocketConnection() method | App in background | Immediately disconnected with WebSocket | - Reconnection If the app is in the foreground and there is no internet connection, the SDK will handle the reconnection of the WebSocket in auto mode. - ## Manual Mode @@ -113,7 +125,7 @@ CometChat.init(appID, appSetting).then( You can manage the connection to the web-socket server using the connect() , disconnect() and ping() methods provided by the SDK. -## Connect to the web-socket server +## Connect to the Web-Socket Server You need to use the connect() method provided by the CometChat class to establish the connection to the web-socket server. Please make sure that the user is logged in to the SDK before calling this method. You can use the CometChat.getLoggedInUser() method to check this. Once the connection is established, you will start receiving all the real-time events for the logged in user @@ -134,7 +146,7 @@ CometChat.connect({ onSuccess: Function, onError: Function }); -## Disconnect from the web-socket server +## Disconnect from the Web-Socket Server You can use the disconnect() method provided by the CometChat class to break the established connection. Once the connection is broken, you will stop receiving all the real-time events for the logged in user. @@ -155,12 +167,10 @@ CometChat.disconnect({ onSuccess: Function, onError: Function }); -### Maintain long-standing background connection +### Maintain Long-Standing Background Connection - To ensure that the WebSocket connection is always alive, you can create a service or background service that calls the CometChat.ping() method in a loop. This will ensure that the ping message is sent to the server every 30 seconds, even if the app is not in the foreground. - You can maintain a long-standing background connection event when your app is in the background, call the CometChat.ping() method within 30 seconds of your app entering the background or after the previous ping() call. @@ -185,3 +195,31 @@ CometChat.ping({ onSuccess: Function, onError: Function }); ## Reconnection If manual mode is enabled and the app is in the foreground, the SDK will automatically reconnect the WebSocket if the internet connection is lost. However, if the app is in the background and the WebSocket is disconnected or you called `CometChat.disconnect()`, then you will need to call the `CometChat.connect()` method to create a new WebSocket connection. + + + +- Use auto mode (default) unless you have a specific need to control the WebSocket lifecycle — it handles reconnection and background disconnection automatically +- In manual mode, always call `CometChat.connect()` after a successful login and before attempting to send or receive messages +- Set up a background task or service to call `CometChat.ping()` every 25 seconds (under the 30-second timeout) if you need background connectivity +- Use the [Connection Status](/sdk/react-native/connection-status) listener alongside manual mode to track when the connection drops and reconnects +- Always call `CometChat.disconnect()` when the user logs out to clean up resources + + + +- **Not receiving real-time events in manual mode**: Ensure you called `CometChat.connect()` after login. In manual mode, the SDK does not connect automatically. +- **Connection drops after 30 seconds in background**: This is expected behavior. Call `CometChat.ping()` within 30 seconds to keep the connection alive. +- **`connect()` fails**: Verify the user is logged in using `CometChat.getLoggedInUser()`. The SDK requires an authenticated user before establishing a WebSocket connection. +- **Messages missed while disconnected**: Fetch missed messages using `MessagesRequest` after reconnecting. The SDK does not queue messages during disconnection. + + + +## Next Steps + + + +Monitor real-time WebSocket connection status + + +Register listeners for users, groups, messages, and calls + + diff --git a/sdk/react-native/mentions.mdx b/sdk/react-native/mentions.mdx index 50627369e..1c072f94d 100644 --- a/sdk/react-native/mentions.mdx +++ b/sdk/react-native/mentions.mdx @@ -1,10 +1,24 @@ --- title: "Mentions" +description: "Learn how to mention users in messages using the CometChat React Native SDK. Use the <@uid:UID> format to tag specific users in text and media message captions." --- + +**Quick Reference** - Mention a user in a message: +```javascript +// Use the format <@uid:UID> to mention users +let messageText = "Hello, <@uid:cometchat-uid-1>"; +let textMessage = new CometChat.TextMessage("RECEIVER_ID", messageText, CometChat.RECEIVER_TYPE.USER); +CometChat.sendMessage(textMessage); +``` + -Mentions in messages enable users to refer to specific individual within a conversation. This is done by using the `<@uid:UID>` format, where `UID` represents the user’s unique identification. + +Available via: [SDK](/sdk/react-native/mentions) | [REST API](/rest-api/messages/list-messages) | [UI Kits](/ui-kit/react-native/core-features#mentions) + + +Mentions in messages enable users to refer to specific individual within a conversation. This is done by using the `<@uid:UID>` format, where `UID` represents the user's unique identification. Mentions are a powerful tool for enhancing communication in messaging platforms. They streamline interaction by allowing users to easily engage and collaborate with particular individuals, especially in group conversations. @@ -13,7 +27,7 @@ Mentions are a powerful tool for enhancing communication in messaging platforms. To send a message with a mentioned user, you must follow a specific format: `<@uid:UID>`. For example, to mention the user with UID `cometchat-uid-1` with the message "`Hello`," your text would be "`Hello, <@uid:cometchat-uid-1>`" - + ```javascript let receiverID = "UID"; let messageText = "Hello, <@uid:cometchat-uid-1>"; @@ -36,7 +50,7 @@ CometChat.sendMessage(textMessage).then( - + ```javascript let receiverID = "GUID"; let messageText = "Hello <@uid:cometchat-uid-1>"; @@ -59,7 +73,7 @@ CometChat.sendMessage(textMessage).then( - + ```typescript let receiverID: string = "UID", messageText: string = "Hello <@uid:cometchat-uid-1>"; @@ -77,7 +91,7 @@ CometChat.sendMessage(textMessage).then( - + ```typescript let receiverID: string = "GUID", messageText: string = "Hello world!", @@ -102,12 +116,114 @@ CometChat.sendMessage(textMessage).then( + +**On Success** — `sendMessage()` with mentions returns the sent message object with `mentionedUsers` populated: +```json +{ + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1772005334, + "role": "default", + "status": "online" + } + ], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "text": "Hello <@uid:cometchat-uid-7>, this is a test mention!", + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1772004288, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1772005334, + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "tags": [] + }, + "entityType": "user" + } + }, + "mentions": { + "cometchat-uid-7": { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1772005334, + "conversationId": "cometchat-uid-6_user_cometchat-uid-7" + } + } + }, + "text": "Hello <@uid:cometchat-uid-7>, this is a test mention!", + "id": "25326", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1772004288, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1772005334, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1772006074, + "updatedAt": 1772006074 +} +``` + + You can mention user in text message and media messages captions + +**Push Notifications & UI Rendering:** While the message format uses `<@uid:UID>`, push notifications are sent with the parsed body containing the actual username — not the raw `<@uid:>` format. For UI rendering with the SDK, use `message.getMentionedUsers()` to get the mentioned user objects (which include both `uid` and `name`) and replace the `<@uid:>` tags in your message bubble accordingly. If you're using a UI Kit, this is handled automatically. + + + ## Mentioned Messages By default, the SDK will fetch all the messages irrespective of the fact that the logged-in user is mentioned or not in the message. The SDK has other optional filters such as tags and blocked relationships. @@ -122,7 +238,7 @@ By default, the SDK will fetch all the messages irrespective of the fact that th To get a list of messages in a conversation where users are mentioned along with the user tags of the mentioned users. - + ```javascript let UID = "UID"; let limit = 30; @@ -149,7 +265,7 @@ messagesRequest.fetchPrevious().then( - + ```javascript let GUID = "GUID"; let limit = 30; @@ -176,7 +292,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let UID: string = "UID", limit: number = 30, @@ -205,7 +321,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -236,12 +352,26 @@ messagesRequest.fetchPrevious().then( + +**On Success** — `mentionsWithTagInfo(true)` returns mentioned users with their tags: +```json +[ + { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "tags": ["vip"] + } +] +``` + + + ## Mentions With Blocked Info To get a list of messages in a conversation where users are mentioned along with the blocked relationship of the mentioned users with the logged-in user. - + ```javascript let UID = "UID"; let limit = 30; @@ -268,7 +398,7 @@ messagesRequest.fetchPrevious().then( - + ```javascript let GUID = "GUID"; let limit = 30; @@ -296,7 +426,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let UID: string = "UID", limit: number = 30, @@ -326,7 +456,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -358,6 +488,21 @@ messagesRequest.fetchPrevious().then( + +**On Success** — `mentionsWithBlockedInfo(true)` returns mentioned users with blocked relationship info: +```json +[ + { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "blockedByMe": false, + "hasBlockedMe": false + } +] +``` + + + ## Get Users Mentioned In a Particular Message To retrieve the list of users mentioned in the particular message, you can use the `message.getMentionedUsers()` method. This method will return an array containing the mentioned users, or an empty array if no users were mentioned in the message. @@ -365,3 +510,70 @@ To retrieve the list of users mentioned in the particular message, you can use t ```javascript message.getMentionedUsers(); ``` + + +**On Success** — `getMentionedUsers()` returns an array of mentioned user objects: +```json +[ + { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "blockedByMe": false, + "hasBlockedMe": false + } +] +``` + + +## Best Practices + + + + Always use the `<@uid:UID>` format when mentioning users. The UID must exactly match the user's unique identifier in CometChat. Incorrect UIDs will not resolve to a valid mention. + + + Before sending a message with mentions, verify that the UIDs you are referencing exist in your CometChat app. Mentioning non-existent UIDs will not throw an error, but the mention will not resolve to a user on the recipient's end. + + + Use `mentionsWithTagInfo(true)` and `mentionsWithBlockedInfo(true)` on your `MessagesRequestBuilder` when you need to display additional context about mentioned users, such as their roles (via tags) or blocked status. Avoid enabling these filters unnecessarily to reduce payload size. + + + Mentions are supported in text messages and media message captions. Ensure your UI handles rendering mentions consistently across both message types. + + + +## Troubleshooting + + + + Ensure you are using the correct `<@uid:UID>` format. The UID must be wrapped exactly as `<@uid:your-uid-here>`. Also verify that the mentioned user exists in your CometChat app. Use `message.getMentionedUsers()` to confirm the SDK parsed the mentions correctly. + + + This typically means the mention format in the message text is incorrect or the UID does not match any registered user. Double-check the message text for proper `<@uid:UID>` syntax and ensure there are no extra spaces or typos in the UID. + + + Make sure you have set `mentionsWithTagInfo(true)` or `mentionsWithBlockedInfo(true)` on your `MessagesRequestBuilder` before calling `fetchPrevious()`. These filters are disabled by default. + + + Verify that you are setting the caption text with the `<@uid:UID>` format on the media message object. Mentions in captions follow the same format as text messages. + + + +## Next Steps + + + + Learn how to send text, media, and custom messages to users and groups. + + + Set up real-time message listeners and fetch message history. + + + Add emoji reactions to messages for richer user interactions. + + + Organize conversations with threaded replies on messages. + + \ No newline at end of file diff --git a/sdk/react-native/message-structure-and-hierarchy.mdx b/sdk/react-native/message-structure-and-hierarchy.mdx index 73e784952..e046e938b 100644 --- a/sdk/react-native/message-structure-and-hierarchy.mdx +++ b/sdk/react-native/message-structure-and-hierarchy.mdx @@ -1,16 +1,25 @@ --- title: "Message Structure And Hierarchy" +description: "Understand the various message categories, types, and statuses in CometChat — including message, custom, action, call, and interactive messages." --- + +**Quick Reference** - Message categories and their common types: +```javascript +// Check message category and type +const category = message.getCategory(); // "message" | "custom" | "action" | "call" | "interactive" +const type = message.getType(); // "text" | "image" | "video" | "audio" | "file" | custom type +``` + -The below diagram helps you better understand the various message categories and types that a CometChat message can belong to. +The diagram below helps you understand the various message categories and types that a CometChat message can belong to. -As you can see in the above diagram, every message belongs to a particular category. A message can belong to either one of the 4 categories +As you can see in the above diagram, every message belongs to a particular category. A message can belong to one of the 5 categories: 1. Message 2. Custom @@ -18,67 +27,104 @@ As you can see in the above diagram, every message belongs to a particular categ 4. Call 5. Interactive -Each category can be further be classified into types. +Each category can be further classified into types. -\#Message A message belonging to the category `message` can be classified into either 1 of the below types: +## Message -1. text - A plain text message -2. image- An image message -3. video- A video message -4. audio- An audio message -5. file- A file message +A message belonging to the category `message` can be classified into one of the following types: + +| Type | Description | +|-------|----------------------| +| text | A plain text message | +| image | An image message | +| video | A video message | +| audio | An audio message | +| file | A file message | ## Custom -In the case of messages that belong to the `custom` category, there are no predefined types. Custom messages can be used by developers to send messages that do not fit in the default category and types provided by CometChat. For messages with the category `custom`, the developers can set their own type to uniquely identify the custom message. A very good example of a custom message would be the sharing of location co-ordinates. In this case, the developer can decide to use the custom message with type set to `location`. +In the case of messages that belong to the `custom` category, there are no predefined types. Custom messages can be used by developers to send messages that do not fit in the default category and types provided by CometChat. For messages with the category `custom`, the developers can set their own type to uniquely identify the custom message. + +A good example of a custom message would be sharing location coordinates. In this case, the developer can decide to use the custom message with type set to `location`. ## Interactive An InteractiveMessage is a specialized object that encapsulates an interactive unit within a chat message, such as an embedded form that users can fill out directly within the chat interface. This enhances user engagement by making the chat experience more interactive and responsive to user input. -form- for interactive form card- for interactive card customInteractive- for custom interaction messages +| Type | Description | +|-------------------|----------------------------------------| +| form | For interactive form messages | +| card | For interactive card messages | +| customInteractive | For custom interaction messages | - -to know about Interactive messages please [Click here](/sdk/react-native/interactive-messages) - +To learn more about Interactive messages, please refer to the [Interactive Messages](/sdk/react-native/interactive-messages) guide. ## Action Action messages are system-generated messages. Messages belonging to the `action` category can further be classified into one of the below types: -1. groupMember - action performed on a group member. -2. message - action performed on a message. +| Type | Description | +|-------------|----------------------------------------| +| groupMember | Action performed on a group member | +| message | Action performed on a message | -Action messages hold another property called `action` which actually determine the action that has been performed For the type `groupMember` the action can be either one of the below: +Action messages hold another property called `action` which determines the action that has been performed. -1. joined - when a group member joins a group -2. left - when a group member leaves a group -3. kicked - when a group member is kicked from the group -4. banned - when a group member is banned from the group -5. unbanned - when a group member is unbanned from the group -6. added - when a user is added to the group -7. scopeChanged - When the scope of a group member is changed. +### groupMember Actions -For the type `message`, the action can be either one of the below: +| Action | Description | +|--------------|------------------------------------------------| +| joined | When a group member joins a group | +| left | When a group member leaves a group | +| kicked | When a group member is kicked from the group | +| banned | When a group member is banned from the group | +| unbanned | When a group member is unbanned from the group | +| added | When a user is added to the group | +| scopeChanged | When the scope of a group member is changed | -1. edited - when a message is edited. -2. deleted - when a message is deleted. +### message Actions -## Call - -Messages with the category `call` are Calling related messages. These can belong to either one of the 2 types +| Action | Description | +|---------|----------------------------| +| edited | When a message is edited | +| deleted | When a message is deleted | -1. audio -2. video - -The call messages have a property called status that helps you figure out the status of the call. The status can be either one of the below values: +## Call -1. initiated - when a is initiated to a user/group -2. ongoing - when the receiver of the call has accepted the call -3. canceled - when the call has been canceled by the initiator of the call -4. rejected - when the call has been rejected by the receiver of the call -5. unanswered - when the call was not answered by the receiver. -6. busy - when the receiver of the call was busy on another call. -7. ended - when the call was successfully completed and ended by either the initiator or receiver. +Messages with the category `call` are calling-related messages. These can belong to either one of the 2 types: + +| Type | Description | +|-------|------------------| +| audio | Audio call | +| video | Video call | + +The call messages have a property called `status` that helps you determine the status of the call: + +| Status | Description | +|-------------|--------------------------------------------------------------------| +| initiated | When a call is initiated to a user/group | +| ongoing | When the receiver of the call has accepted the call | +| canceled | When the call has been canceled by the initiator of the call | +| rejected | When the call has been rejected by the receiver of the call | +| unanswered | When the call was not answered by the receiver | +| busy | When the receiver of the call was busy on another call | +| ended | When the call was successfully completed and ended by either party | + +## Next Steps + + + + Start sending text, media, and custom messages + + + Build forms, cards, and custom interactive messages + + + Listen for and handle incoming messages in real-time + + + Review the fundamental building blocks of CometChat + + diff --git a/sdk/react-native/messaging-overview.mdx b/sdk/react-native/messaging-overview.mdx index 517fb6db6..3d2ed42a0 100644 --- a/sdk/react-native/messaging-overview.mdx +++ b/sdk/react-native/messaging-overview.mdx @@ -1,12 +1,446 @@ --- title: "Messaging" sidebarTitle: "Overview" +description: "Overview of CometChat messaging capabilities — send, receive, and fetch message history for text, media, custom, and interactive messages." --- + +**Quick Reference** - Core messaging methods: +```javascript +// Send a text message +const textMessage = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); +await CometChat.sendMessage(textMessage); + +// Listen for incoming messages +CometChat.addMessageListener("listener-id", new CometChat.MessageListener({ + onTextMessageReceived: (msg) => console.log("Text:", msg), + onMediaMessageReceived: (msg) => console.log("Media:", msg), + onCustomMessageReceived: (msg) => console.log("Custom:", msg), +})); +``` + + + +Available via: [SDK](/sdk/react-native/messaging-overview) | [REST API](/rest-api/messages) | [UI Kits](/ui-kit/react-native/core-features#instant-messaging) + Messaging is one of the core features of CometChat. We've thoughtfully created methods to help you send, receive and fetch message history. At the minimum, you must add code for [sending messages](/sdk/react-native/send-message) and [receiving messages](/sdk/react-native/receive-messages). Once you've implemented that, you can proceed to more advanced features like [typing indicators](/sdk/react-native/typing-indicators) and [delivery & read receipts](/sdk/react-native/delivery-read-receipts). + +### Send a Message + +Use `CometChat.sendMessage()` to send a text message to a user or group. The method returns a `TextMessage` object on success. + + +**On Success** — `console.log("Message sent successfully:", message)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "text": "Hello", + "resource": "REACT_NATIVE-4_0_13-398e7dd2-3481-44ed-8837-eadf1c9c6f5d-1771320626645", + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771320632, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771320647, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "tags": [] + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "pending" + } + }, + "text": "Hello", + "id": "25182", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771320632, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771320647, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771320772, + "updatedAt": 1771320772, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} +``` + +**On Failure** — `console.log("Message sending failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in. Please log in before sending a message.", + "details": {} +} +``` + + +### Receive Messages in Real Time + +Use `CometChat.addMessageListener()` to listen for incoming text, media, and custom messages while your app is running. + + +**onTextMessageReceived** — `console.log("Text message received successfully", textMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771320632, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771320647, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_13-6cfc6ba5-feae-42a0-a773-000d4e41a333-1771320636087", + "text": "Hello" + }, + "text": "Hello", + "id": "25180", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771320647, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771320632, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771320657, + "updatedAt": 1771320657, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} +``` + +**onMediaMessageReceived** — `console.log("Media message received successfully", mediaMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "jpg", + "mimeType": "image/jpeg", + "name": "44.jpg", + "size": 142099, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771320861_514214897_9876c9a3f300f29c8ee619765c1ad768.jpg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771320632, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771320859, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_13-6cfc6ba5-feae-42a0-a773-000d4e41a333-1771320636087", + "type": "image", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771320861_514214897_9876c9a3f300f29c8ee619765c1ad768.jpg" + }, + "id": "25183", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771320859, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771320632, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771320862, + "updatedAt": 1771320862 +} +``` + +**onCustomMessageReceived** — `console.log("Custom message received successfully", customMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "test-custom", + "receiverType": "user", + "category": "custom", + "customData": { + "greeting": "Hello from custom message!", + "timestamp": 1771324022864 + }, + "data": { + "customData": { + "greeting": "Hello from custom message!", + "timestamp": 1771324022864 + }, + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771323089, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771323567, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-5cebfc4b-80f7-44df-8a0a-5a760ffe5239-1771321973734", + "text": "Sent a custom message" + }, + "id": "25191", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771323567, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323089, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771324025, + "updatedAt": 1771324025, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} +``` + + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Listen for real-time messages and fetch missed messages + + + Show real-time typing status in conversations + + + Track when messages are delivered and read + + diff --git a/sdk/react-native/overview.mdx b/sdk/react-native/overview.mdx index da1eadb45..66a78f663 100644 --- a/sdk/react-native/overview.mdx +++ b/sdk/react-native/overview.mdx @@ -1,376 +1,430 @@ --- title: "Overview" +description: "Get started with CometChat React Native SDK - initialize, authenticate users, and integrate chat functionality into your React Native application." --- + +**Quick Reference** - Copy-paste ready initialization and login: +```javascript +useEffect(() => { + const initCometChat = async () => { + const appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .autoEstablishSocketConnection(true) + .build(); + await CometChat.init("APP_ID", appSetting); + + // Login user (check if already logged in first) + const loggedInUser = await CometChat.getLoggedinUser(); + if (!loggedInUser) { + await CometChat.login("USER_UID", "AUTH_KEY"); + } + }; + initCometChat(); +}, []); +``` + This guide demonstrates how to add chat to a React Native application using CometChat. Before you begin, we strongly recommend you read the [Key Concepts](/sdk/react-native/key-concepts) guide. #### I want to integrate with my app -1. [Get your application keys](overview#get-your-application-keys) -2. [Add the CometChat dependency](overview#add-the-cometchat-dependency) -3. [Initialize CometChat](overview#initialize-cometchat) -4. [Register and Login your user](overview#register-and-login-your-user) -5. [Integrate our UI Kits](overview#integrate-our-ui-kits) +1. [Get your Application Keys](#get-your-application-keys) +2. [Add the CometChat Dependency](#add-the-cometchat-dependency) +3. [Initialize CometChat](#initialize-cometchat) +4. [Register and Login your user](#register-and-login-your-user) +5. [Integrate our UI Kits](#integrate-our-ui-kits) #### I want to explore a sample app (includes UI) Open the app folder in your favorite code editor and follow the steps mentioned in the `README.md` file. -[React Native Sample App](https://github.com/cometchat-pro/react-native-chat-app) + + Explore a complete React Native chat application with UI components + -### Get your Application Keys +## Get your Application Keys [Signup for CometChat](https://app.cometchat.com) and then: -1. Create a new app -2. Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** + + + Create a new application in your CometChat dashboard + + + Head over to the **API & Auth Keys** section and note the **Auth Key**, **App ID** & **Region** + + ## Add the CometChat Dependency Install the package as an NPM module: - -```bash -npm install @cometchat/chat-sdk-react-native -``` - - - + + ```bash + npm install @cometchat/chat-sdk-react-native + ``` + + + ```bash + yarn add @cometchat/chat-sdk-react-native + ``` + **To integrate the CometChat React Native SDK, you need to install one more dependency.** -1. Async-Storage: +### Async-Storage - -```bash -npm install @react-native-async-storage/async-storage -``` - - - + + ```bash + npm install @react-native-async-storage/async-storage + ``` + + + ```bash + yarn add @react-native-async-storage/async-storage + ``` + +v2.4+ onwards, Voice & Video Calling functionality has been moved to a separate library. In case you plan to use the calling feature, please install the Calling dependency (`@cometchat/calls-sdk-react-native`). -v2.4+ onwards, Voice & Video Calling functionality has been moved to a separate library. In case you plan to use the calling feature, please install the Calling dependency (@cometchat/calls-sdk-react-native).\ -\ -`npm install @cometchat/calls-sdk-react-native`\ -\ -The calling component requires some configuration. Please follow the steps mentioned [here](/sdk/react-native/overview#calling-component-configuration). +```bash +npm install @cometchat/calls-sdk-react-native +``` +The calling component requires some configuration. Please follow the steps mentioned in the [Calling Component Configuration](#calling-component-configuration) section below. ## Calling Component Configuration For `@cometchat/calls-sdk-react-native`, please make sure you add the following additional dependencies & permissions. - - +### Required Dependencies + ```json { - "@cometchat/chat-sdk-react-native": "^4.0.18", - "@react-native-async-storage/async-storage": "^2.2.0", - "@react-native-community/netinfo": "^11.4.1", - "react-native-background-timer": "^2.4.1", - "react-native-callstats": "^3.73.22", - "react-native-webrtc": "^124.0.6" + "@cometchat/chat-sdk-react-native": "^4.0.18", + "@react-native-async-storage/async-storage": "^2.2.0", + "@react-native-community/netinfo": "^11.4.1", + "react-native-background-timer": "^2.4.1", + "react-native-callstats": "^3.73.22", + "react-native-webrtc": "^124.0.6" } ``` - - - - -#### Permissions: - -**Android:** +### Permissions - -```xml - - - - - -``` - - - + + Add the following permissions to your `AndroidManifest.xml`: + + ```xml + + + + + + ``` + + + Add the following keys to your `Info.plist`: + + ```xml + NSCameraUsageDescription + This is for Camera permission + NSMicrophoneUsageDescription + This is for Mic permission + ``` + -**iOS:** - - - -```xml -NSCameraUsageDescription -This is for Camera permission -NSMicrophoneUsageDescription -This is for Mic permission -``` +### Platform-Specific Configuration - + + + Go to the `./android` folder and open the project level `build.gradle` file. Add all repository URLs in the repositories block under the `allprojects` section. Also in the same file in the `buildscript` section in the `ext` block, make sure you have set **minSdkVersion** to **24**. - - -#### Android: - -Goto ./android folder and open project level build.gradle file and add all repository URLs in the repositories block under the allprojects section. Also in the same file in buildscript section in the ext block make sure you have set **minSdkVersio**n to **24**. - - - -```gradle -allprojects { -repositories { - maven { - url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/" - } -} -} -``` - - - - - -Also in the same file in buildscript section in the ext block make sure you have set minSdkVersion to 24. - - - -```gradle -buildscript { - ext { - buildToolsVersion = "29.0.2" - minSdkVersion = 24 - compileSdkVersion = 29 - targetSdkVersion = 29 - } -} -``` - - - - - -#### iOS: - -Please update the minimum target version in the Podfile. Goto ./ios folder and open the Podfile. In the Podfile update the platform version to `11.0` - - - -``` -platform :ios, '11.0' -``` + **Add Repository URL:** - + ```gradle + allprojects { + repositories { + maven { + url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/" + } + } + } + ``` + + **Set Minimum SDK Version:** + + ```gradle + buildscript { + ext { + buildToolsVersion = "29.0.2" + minSdkVersion = 24 + compileSdkVersion = 29 + targetSdkVersion = 29 + } + } + ``` + + + Please update the minimum target version in the Podfile. Go to the `./ios` folder and open the Podfile. In the Podfile, update the platform version to `11.0`: - + ```ruby + platform :ios, '11.0' + ``` -Open the `ios/App` folder and run `pod install` this will create an `App.xcworkspace` open this and run the app. + Open the `ios/App` folder and run `pod install`. This will create an `App.xcworkspace` file. Open this and run the app. + + ## Initialize CometChat -The `init(`)`method initializes the settings required for CometChat. The`init()\` method takes the below parameters: +The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters: -1. appID - You CometChat App ID -2. appSettings - An object of the AppSettings class can be created using the AppSettingsBuilder class. The region field is mandatory and can be set using the `setRegion()` method. +| Parameter | Description | +|-----------|-------------| +| `appID` | Your CometChat App ID | +| `appSettings` | An object of the `AppSettings` class created using the `AppSettingsBuilder` class | -The `AppSettings` class allows you to configure two settings: +The `AppSettings` class allows you to configure the following settings: -* **Region**: The region where your app was created. -* [Presence Subscription](/sdk/react-native/user-presence): Represents the subscription type for user presence (real-time online/offline status) -* **autoEstablishSocketConnection(boolean value)**: This property takes a boolean value which when set to true informs the SDK to manage the web-socket connection internally. If set to false, it informs the SDK that the web-socket connection will be managed manually. The default value for this parameter is true. For more information on this, please check the [Managing connections manually](/sdk/react-native/managing-web-sockets-connections-manually) section. The default value for this property is **true.** -* **overrideAdminHost(adminHost: string)**: This method takes the admin URL as input and uses this admin URL instead of the default admin URL. This can be used in case of dedicated deployment of CometChat. -* **overrideClientHost(clientHost: string)**: This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat. +| Setting | Description | +|---------|-------------| +| **Region** | The region where your app was created (mandatory) | +| **Presence Subscription** | Represents the subscription type for user presence (real-time online/offline status). See [Presence Subscription](/sdk/react-native/user-presence) | +| **autoEstablishSocketConnection(boolean)** | When set to `true`, the SDK manages the web-socket connection internally. When set to `false`, you manage the connection manually. Default: `true`. See [Managing connections manually](/sdk/react-native/managing-web-sockets-connections-manually) | +| **overrideAdminHost(adminHost: string)** | Uses a custom admin URL instead of the default. Used for dedicated CometChat deployments | +| **overrideClientHost(clientHost: string)** | Uses a custom client URL instead of the default. Used for dedicated CometChat deployments | -You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `index.js` file. +You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `App.tsx` file. - -```javascript -let appID = "APP_ID"; -let region = "REGION"; -let appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); -CometChat.init(appID, appSetting).then( - () => { - console.log("Initialization completed successfully"); - }, - (error) => { - console.log("Initialization failed with error:", error); - } -); -``` - - - - -```javascript -let appID: string = "APP_ID", - region: string = "APP_REGION", - appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); -CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); - }, - (error: CometChat.CometChatException) => { - console.log("Initialization failed with error:", error); - } -); -``` - - - + + ```javascript + let appID = "APP_ID"; + let region = "REGION"; + + // Build app settings with presence subscription and auto socket connection + let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + + // Initialize CometChat + CometChat.init(appID, appSetting).then( + () => { + console.log("Initialization completed successfully"); + }, + (error) => { + console.log("Initialization failed with error:", error); + } + ); + ``` + + + ```typescript + let appID: string = "APP_ID", + region: string = "APP_REGION", + + // Build app settings with presence subscription and auto socket connection + let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + + // Initialize CometChat + CometChat.init(appID, appSetting).then( + (initialized: boolean) => { + console.log("Initialization completed successfully", initialized); + }, + (error: CometChat.CometChatException) => { + console.log("Initialization failed with error:", error); + } + ); + ``` + + Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` with your **App Region** in the above code. + ## Register and Login your user Once initialization is successful, you will need to create a user. To create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. - -```javascript -let authKey = "AUTH_KEY"; -let uid = "user1"; -let name = "Kevin"; - -let user = new CometChat.User(uid); - -user.setName(name); - -CometChat.createUser(user, authKey).then( - (user) => { - console.log("user created", user); - }, - (error) => { - console.log("error", error); - } -); -``` - - - - -```javascript -let authKey: string = "AUTH_KEY", - UID: string = "user1", - name: string = "Kevin"; - -var user = new CometChat.User(UID); -user.setName(name); - -CometChat.createUser(user, authKey).then( - (user: CometChat.User) => { - console.log("user created", user); - }, - (error: CometChat.CometChatException) => { - console.log("error", error); - } -); -``` - - - + + ```javascript + let authKey = "AUTH_KEY"; + let uid = "user1"; + let name = "Kevin"; + + // Create a new user object + let user = new CometChat.User(uid); + user.setName(name); + + // Register the user with CometChat + CometChat.createUser(user, authKey).then( + (user) => { + console.log("user created", user); + }, + (error) => { + console.log("error", error); + } + ); + ``` + + + ```typescript + let authKey: string = "AUTH_KEY", + UID: string = "user1", + name: string = "Kevin"; + + // Create a new user object + var user = new CometChat.User(UID); + user.setName(name); + + // Register the user with CometChat + CometChat.createUser(user, authKey).then( + (user: CometChat.User) => { + console.log("user created", user); + }, + (error: CometChat.CometChatException) => { + console.log("error", error); + } + ); + ``` + + Make sure that `UID` and `name` are specified as these are mandatory fields to create a user. + Once you have created the user successfully, you will need to log the user into CometChat using the `login()` method. We recommend you call the CometChat `login()` method once your user logs into your app. The `login()` method needs to be called only once. - - -This straightforward authentication method is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [Auth Token](/sdk/react-native/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security. - - + +**Security Warning:** This straightforward authentication method using Auth Key is ideal for proof-of-concept (POC) development or during the early stages of application development. For production environments, however, we strongly recommend using an [Auth Token](/sdk/react-native/authentication-overview#login-using-auth-token) instead of an Auth Key to ensure enhanced security. + - -```javascript -let UID = "cometchat-uid-1"; -let authKey = "AUTH_KEY"; - -CometChat.getLoggedinUser().then( - (user) => { - if (!user) { - CometChat.login(UID, authKey).then( - (user) => { - console.log("Login Successful:", { user }); - }, - (error) => { - console.log("Login failed with exception:", { error }); + + ```javascript + let UID = "cometchat-uid-1"; + let authKey = "AUTH_KEY"; + + // Check if user is already logged in + CometChat.getLoggedinUser().then( + (user) => { + if (!user) { + // Login the user if not already logged in + CometChat.login(UID, authKey).then( + (user) => { + console.log("Login Successful:", { user }); + }, + (error) => { + console.log("Login failed with exception:", { error }); + } + ); } - ); - } - }, - (error) => { - console.log("Some Error Occured", { error }); - } -); -``` - - - - -```javascript -var UID: string = "cometchat-uid-1", - authKey: string = "AUTH_KEY"; - -CometChat.getLoggedinUser().then( - (user: CometChat.User) => { - if (!user) { - CometChat.login(UID, authKey).then( - (user: CometChat.User) => { - console.log("Login Successful:", { user }); - }, - (error: CometChat.CometChatException) => { - console.log("Login failed with exception:", { error }); + }, + (error) => { + console.log("Some Error Occured", { error }); + } + ); + ``` + + + ```typescript + var UID: string = "cometchat-uid-1", + authKey: string = "AUTH_KEY"; + + // Check if user is already logged in + CometChat.getLoggedinUser().then( + (user: CometChat.User) => { + if (!user) { + // Login the user if not already logged in + CometChat.login(UID, authKey).then( + (user: CometChat.User) => { + console.log("Login Successful:", { user }); + }, + (error: CometChat.CometChatException) => { + console.log("Login failed with exception:", { error }); + } + ); } - ); - } - }, - (error: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); - } -); -``` - - - + }, + (error: CometChat.CometChatException) => { + console.log("Some Error Occured", { error }); + } + ); + ``` + + Make sure you replace the `AUTH_KEY` with your CometChat **Auth Key** in the above code. + - - -We have set-up 5 users for testing having UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`. - - + +**Test Users Available:** We have set up 5 users for testing with UIDs: `cometchat-uid-1`, `cometchat-uid-2`, `cometchat-uid-3`, `cometchat-uid-4` and `cometchat-uid-5`. + The `login()` method returns the `User` object containing all the information of the logged-in user. - -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. - +**UID Format:** UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. ## Integrate our UI Kits -Please refer to the [React Native UI Kit](/ui-kit/react-native/overview)section to integrate React Native UI Kit inside your app. +Please refer to the [React Native UI Kit](/ui-kit/react-native/overview) section to integrate React Native UI Kit inside your app. + + + + - Always call `init()` before any other CometChat method + - Call `init()` on app startup (preferably in `App.tsx`) + - Use `getLoggedinUser()` to check login state before calling `login()` + - Store user credentials securely and never expose Auth Keys in client-side code for production + - Use Auth Token instead of Auth Key for production environments + + + - **Initialization fails:** Verify your App ID and Region are correct + - **Login fails:** Ensure the user exists or create them first using `createUser()` + - **Network errors:** Check internet connectivity and firewall settings + - **Calling not working:** Verify all calling dependencies are installed and permissions are granted + - **iOS build fails:** Run `pod install` in the `ios` directory after adding dependencies + + + +## Next Steps + + + + Understand the fundamental concepts of CometChat + + + Learn about secure authentication methods including Auth Tokens + + + Start sending text, media, and custom messages + + + Add pre-built UI components to your app + + diff --git a/sdk/react-native/presenter-mode.mdx b/sdk/react-native/presenter-mode.mdx index 802886268..f94b70b5c 100644 --- a/sdk/react-native/presenter-mode.mdx +++ b/sdk/react-native/presenter-mode.mdx @@ -1,8 +1,27 @@ --- title: "Presenter Mode" +description: "Implement presenter mode in your React Native app — allow up to 5 presenters to share video, audio, and screen with up to 100 viewers using CometChat Calls SDK." --- + +**Quick Reference** - Start a presentation session: +```javascript +// Configure presenter settings +let presenterSettings = new CometChatCalls.PresenterSettingsBuilder() + .setIsPresenter(true) // false for viewer + .enableDefaultLayout(true) + .setCallEventListener(callListener) + .build(); + +// Render presenter component +// +``` + + + +**Available via:** SDK | UI Kits + ## Overview @@ -25,9 +44,9 @@ Using this feature developers can create experiences such as: ### About this guide -This guide demonstrates how to start a presentation into an React Native application. Before you begin, we strongly recommend you read the calling setup guide. +This guide demonstrates how to start a presentation into an React Native application. Before you begin, we strongly recommend you read the [calling setup guide](/sdk/react-native/calling-setup). -Before starting a call session you have to generate a call token. You need to call this method for the call token. +Before starting a call session you have to [generate a call token](/sdk/react-native/direct-call#generate-call-token). ### Start Presentation Session @@ -59,7 +78,7 @@ render(){ -## **Listeners** +## Listeners Listeners can be added in two ways the first one is to use `.setCallEventListener(listeners : OngoingCallListener)` method in `CallSettingsBuilder` or `PresenterSettingsBuilder` class. The second way is to use `CometChatCalls.addCallEventListener(name: string, callListener: OngoingCallListener)` by this you can add multiple listeners and remove the specific listener by their name `CometChatCalls.removeCallEventListener(name: string)` @@ -101,6 +120,133 @@ useEffect(() => { + +Always remove call event listeners when the component unmounts using `CometChatCalls.removeCallEventListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. + + + +**On Event** — `onUserJoined` returns a user object when a participant joins the presentation: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `id` | string | Internal session participant ID | `"cd530243"` | +| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | +| `isVideoMuted` | boolean | Whether user's video is muted | `true` | +| `isAudioMuted` | boolean | Whether user's audio is muted | `false` | +| `isLocalUser` | boolean | Whether this is the local user | `false` | + + + + +**On Event** — `onUserLeft` returns a user object when a participant leaves the presentation: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `id` | string | Internal session participant ID | `"cd530243"` | +| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | +| `isVideoMuted` | boolean | Whether user's video was muted | `true` | +| `isAudioMuted` | boolean | Whether user's audio was muted | `false` | + + + + +**On Event** — `onUserListUpdated` returns an array of all current participants in the presentation: + + + +**User Array:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of user objects | [See below ↓](#on-user-list-updated-user-object) | + + + +**User Object (each item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | + + + + +**On Event** — `onAudioModesUpdated` returns an array of available audio output modes: + + + +**Audio Modes Array:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of audio mode objects | [See below ↓](#on-audio-modes-updated-mode-object) | + + + +**Audio Mode Object (each item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Type of audio output device | `"SPEAKER"` | +| `selected` | boolean | Whether this mode is currently selected | `true` | + + + + +**On Event** — `onRecordingStarted` returns information about the user who started the recording: + + + +**RecordingStartedBy Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user who started recording | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `recordId` | string | Unique identifier for this recording session | `"noujausedimwfhwl"` | +| `id` | string | Internal session participant ID | `"042d0440"` | +| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | +| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | +| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | + + + + +**On Event** — `onRecordingStopped` returns information about the user who stopped the recording: + + + +**RecordingStoppedBy Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user who stopped recording | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `id` | string | Internal session participant ID | `"042d0440"` | +| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | +| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | +| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | + + + The `CometChatCallsEventsListener` listener provides you with the below callback methods: | Callback Method | Description | @@ -146,3 +292,56 @@ The options available for customization of calls are: In case you wish to achieve a completely customised UI for the Calling experience, you can do so by embedding default android buttons to the screen as per your requirement and then use the below methods to achieve different functionalities for the embedded buttons. For the use case where you wish to align your own custom buttons and not use the default layout provided by CometChat you can embed the buttons in your layout and use the below methods to perform the corresponding operations: + +## Best Practices + + + + Always explicitly set `setIsPresenter(true)` for presenters and `setIsPresenter(false)` for viewers. Viewers cannot send audio, video, or screen streams — this is enforced by the SDK, not just the UI. + + + Presenter Mode supports a maximum of 5 concurrent presenters. If your app allows dynamic role switching, enforce this limit in your logic before calling `setIsPresenter(true)` for additional users. + + + Always remove call event listeners in your component's cleanup function (e.g., the return function of `useEffect`). Orphaned listeners can cause memory leaks and duplicate event handling. + + + Call tokens are session-specific and time-limited. Generate them right before starting the presentation session rather than caching them for extended periods. + + + +## Troubleshooting + + + + Verify that `setIsPresenter(false)` is set for viewer participants. If a viewer is incorrectly set as a presenter, they will have access to media controls. + + + Ensure the `CometChatCalls.PresenterComponent` is wrapped in a `View` with `flex: 1` or explicit dimensions. Also confirm that both `presenterSettings` and `callToken` props are provided and not `null`. + + + Check that the listener is registered before the presentation session starts. If using `addCallEventListener`, ensure the `listenerId` is unique and hasn't been overwritten. Also verify the Calls SDK has been initialized via `CometChatCalls.init()`. + + + Presenter Mode supports up to 100 total participants (presenters + viewers). If users can't join, check the current participant count in your session. + + + +--- + +## Next Steps + + + + Start and manage standard call sessions with full configuration options + + + Record presentation sessions for playback and compliance + + + Customize the main video container and participant tiles + + + Install dependencies, configure permissions, and initialize the Calls SDK + + \ No newline at end of file diff --git a/sdk/react-native/push-notification-html-stripping.mdx b/sdk/react-native/push-notification-html-stripping.mdx new file mode 100644 index 000000000..84d39b45f --- /dev/null +++ b/sdk/react-native/push-notification-html-stripping.mdx @@ -0,0 +1,258 @@ +--- +title: "Push Notification Content Customization" +description: "Learn how to intercept and modify push notification content before display in React Native." +--- + + +## Overview + +This guide demonstrates how to intercept push notification content before rendering and clean up the notification body or title. The example below shows how to strip HTML tags from the notification body, but the same approach can be used to apply any regex-based transformation to the notification title or body before triggering the push notification. + + +This solution is specific to React Native. On some Android devices, the OS handles HTML tag stripping by default. Consider this example as a reference for modifying any content in the notification body or title before display. + + +The approach strips HTML tags at the notification display layer only, without modifying: +- The message payload +- SDK logic +- Chat UI rendering + +This means rich text remains unchanged inside the chat UI while push notifications display clean, readable text across foreground, background, and killed states. + +## Android Implementation + +On Android, use FCM (`@react-native-firebase/messaging`) to receive push notifications and route all notification flows through a single handler (e.g., `displayLocalNotification`) for both `messaging().onMessage()` (foreground) and `messaging().setBackgroundMessageHandler()` (background/killed). This lets you clean the content before displaying it. + +### Add the Utility Function + +Create or update your helper file with the `stripHtmlTags` function: + +```typescript +// src/utils/helper.ts +export function stripHtmlTags(text: string): string { + if (!text) return text; + return text + .replace(/<[^>]+>/g, '') + .replace(/ /g, ' ') + .replace(/&/g, '&') + .replace(/</g, '<') + .replace(/>/g, '>') + .replace(/"/g, '"') + .replace(/'/g, "'") + .replace(/\s+/g, ' ') + .trim(); +} +``` + +### Display Notifications with Cleaned Content + +```typescript +import { stripHtmlTags } from '../utils/helper'; + +export async function displayLocalNotification(remoteMessage: any) { + try { + const { title, body } = remoteMessage.data || {}; + const cleanedBody = stripHtmlTags(body); + // You can also intercept and modify the title the same way + + await notifee.displayNotification({ + title: title || 'New Message', + body: cleanedBody || 'You received a new message', + android: { + channelId: 'default', + pressAction: { + id: 'default', + }, + }, + }); + } catch (error) { + console.error('displayLocalNotification error', error); + } +} +``` + +### How It Works on Android + +| State | Flow | +|-------|------| +| Foreground | `App.tsx` → `messaging().onMessage()` → `displayLocalNotification()` | +| Background/Killed | `index.js` → `messaging().setBackgroundMessageHandler()` → `displayLocalNotification()` | + +Since both paths call `displayLocalNotification()`, HTML stripping happens automatically for all notification states. + +## iOS Implementation + +On iOS, push notifications are delivered via APNs (Apple Push Notification service). To modify notification content before display, use a Notification Service Extension — a native iOS mechanism that intercepts APNs payloads before they are shown to the user. + +A [Notification Service Extension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension) intercepts push notifications before they are displayed, allowing you to modify the content. + +### Create the Notification Service Extension + + + +In Xcode, go to **File → New → Target → Notification Service Extension**. Name it `NotificationService` and click **Finish**. + +Once added, you should see `NotificationService` listed under TARGETS in your project: + + + Xcode showing NotificationService listed under TARGETS in the main app + + + + +When prompted to activate the new scheme, click **Activate**. + + + +Replace the contents of `NotificationService.swift` with the following: + +```swift +import UserNotifications + +class NotificationService: UNNotificationServiceExtension { + + var contentHandler: ((UNNotificationContent) -> Void)? + var bestAttemptContent: UNMutableNotificationContent? + + override func didReceive( + _ request: UNNotificationRequest, + withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void + ) { + self.contentHandler = contentHandler + bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) + + if let bestAttemptContent = bestAttemptContent { + // Strip HTML tags from the notification body + if let body = bestAttemptContent.body as String? { + bestAttemptContent.body = stripHtmlTags(body) + } + + // Strip HTML tags from the notification title if needed + if let title = bestAttemptContent.title as String? { + bestAttemptContent.title = stripHtmlTags(title) + } + + contentHandler(bestAttemptContent) + } + } + + override func serviceExtensionTimeWillExpire() { + if let contentHandler = contentHandler, let bestAttemptContent = bestAttemptContent { + contentHandler(bestAttemptContent) + } + } + + private func stripHtmlTags(_ text: String) -> String { + guard !text.isEmpty else { return text } + var result = text + // Remove HTML tags + result = result.replacingOccurrences( + of: "<[^>]+>", + with: "", + options: .regularExpression + ) + // Decode common HTML entities + let entities: [String: String] = [ + " ": " ", + "&": "&", + "<": "<", + ">": ">", + """: "\"", + "'": "'" + ] + for (entity, replacement) in entities { + result = result.replacingOccurrences(of: entity, with: replacement) + } + // Collapse whitespace + result = result.replacingOccurrences( + of: "\\s+", + with: " ", + options: .regularExpression + ).trimmingCharacters(in: .whitespacesAndNewlines) + return result + } +} +``` + + + +### Required iOS Configuration + +| Setting | Details | +|---------|---------| +| Team & Signing | The extension target must have the same team and signing configuration as your main app target | +| Bundle Identifier | Must be a child of your main app's bundle ID (e.g., `com.yourapp.NotificationService`) | +| Bridging Header | If you see a bridging header error, clear the **Objective-C Bridging Header** field in the extension's Build Settings | +| Push Payload | Your APNs payload must include `"mutable-content": 1` for the extension to intercept notifications | +| Deployment Target | The extension's deployment target must match or be lower than your main app's deployment target | + +Select the `NotificationService` target and verify the bundle identifier is a child of your main app's bundle ID: + + + Xcode NotificationService target General tab showing bundle identifier + + + +The Notification Service Extension's **Minimum Deployment** target must match your main app's minimum deployment target. The extension runs as a separate process alongside your main app — if the deployment targets don't match, iOS will silently skip the extension and notifications will display unmodified. + + +If you encounter a bridging header error, select the `NotificationService` target → **Build Settings**, search for "bridging", and clear the **Objective-C Bridging Header** value: + + + Xcode Build Settings showing Objective-C Bridging Header field for NotificationService target + + +Verify your main app target's **Build Phases** includes `NotificationService.appex` after a successful build under **Embed Foundation Extensions**: + + + Xcode Build Phases showing Embed Foundation Extensions with NotificationService.appex + + + +If your project uses React Native Firebase (e.g., for FCM on Android), you may also see `[CP-User] [RNFB] Core Configuration` in Build Phases. This is a CocoaPods build phase and does not affect the Notification Service Extension itself. + + +## Testing + +### Android (FCM) +1. Send a message containing HTML tags (e.g., `Hello World`) from another user +2. Verify the push notification displays clean text (`Hello World`) instead of raw HTML +3. Test across all app states: + - Foreground (`messaging().onMessage()` → `displayLocalNotification()`) + - Background/Killed (`messaging().setBackgroundMessageHandler()` → `displayLocalNotification()`) + +### iOS (APNs) +1. Test on a physical device — Notification Service Extensions do not run on the iOS Simulator +2. Send a message containing HTML tags from another user +3. Verify the push notification displays clean text in both background and killed states +4. Confirm that the chat UI still renders the rich text with formatting intact in both platforms + + + +- **Bridging Header Error**: If you get a build error related to the Objective-C Bridging Header in the NotificationService target, go to the extension's **Build Settings → Objective-C Bridging Header** and clear the value. +- **Build Cycle Error**: If you see a build cycle error after adding the extension (common in projects using CocoaPods), go to your main app target's **Build Phases**, find **Embed Foundation Extensions**, and ensure `NotificationService.appex` is listed correctly. +- **Extension Not Working on Simulator**: Notification Service Extensions do not run on the iOS Simulator. Test on a physical device. +- **Extension Not Intercepting Notifications**: Ensure your APNs payload includes `"mutable-content": 1`. Without this flag, iOS will not route the notification through your extension. +- **Build Fails After Adding Extension**: Verify the extension's deployment target matches your main app. Also ensure the extension's bundle ID is a child of the main app's bundle ID (e.g., `com.yourapp.NotificationService`). + + + +- **Android**: Route all FCM notification flows through a single handler function to ensure consistent content transformation +- **iOS**: The Notification Service Extension handles all APNs notifications automatically — no additional routing needed +- Keep the `stripHtmlTags` function in a shared utility file so it can be reused across your app +- Handle `serviceExtensionTimeWillExpire()` gracefully on iOS — deliver the best available content if processing takes too long +- Test on physical iOS devices since Notification Service Extensions do not run on the simulator +- Consider logging stripped content during development to verify the regex handles all edge cases in your notification payloads + + + +## Next Steps + + + +Learn how to send different types of messages + + +Handle incoming messages in real time + + diff --git a/sdk/react-native/rate-limits.mdx b/sdk/react-native/rate-limits.mdx index 17581b144..7c7f6ecad 100644 --- a/sdk/react-native/rate-limits.mdx +++ b/sdk/react-native/rate-limits.mdx @@ -1,34 +1,70 @@ --- title: "Rate Limits" +description: "Understand CometChat REST API rate limits, how to monitor usage via response headers, and how to handle rate limit errors." --- + +**Quick Reference** - Key rate limits at a glance: +| Operation Type | Limit | +|----------------|--------------------------| +| Core | 10,000 requests/minute | +| Standard | 20,000 requests/minute | + -### CometChat REST API Rate Limits +## CometChat REST API Rate Limits - -The rate limits below are for general applications. Rate limits can be adjusted on a per need basis, depending on your use-case and plan. The rate limits are cumulative. For example: If the rate limit for core operations is 100 requests per minute, then you can either login a user, add user to a group, remove a user from a group, etc for total 100 requests per minute. - +The rate limits below are for general applications. Rate limits can be adjusted on a per-need basis, depending on your use case and plan. The rate limits are cumulative. For example: if the rate limit for core operations is 10,000 requests per minute, then you can login a user, add a user to a group, remove a user from a group, etc. for a combined total of 10,000 requests per minute. -1. **Core Operations:** Core operations are rate limited to `10,000` requests per minute. Core operations include user login, create/delete user, create/join group cumulatively. -2. **Standard Operations:** Standard operations are rate limited to `20,000` requests per minute. Standard operations include all other operations cumulatively. - -## What happens when rate limit is reached ? - -The request isn't processed and a response is sent containing a 429 response code. Along with the response code there will be couple of headers sent which specifies the time in seconds that you must wait before you can try request again. - -`Retry-After: 15` - -`X-Rate-Limit-Reset: 1625143246` - -## Is there any endpoint that returns rate limit of all resources ? - -No, we don't provide a rate-limit endpoint. - -However, we do provide the following response headers that you can use to confirm the app's current rate limit and monitor the number of requests remaining in the current minute: - -`X-Rate-Limit: 700` - -`X-Rate-Limit-Remaining: 699` +| Operation Type | Rate Limit | Examples | +|-------------------------|-----------------------------|-----------------------------------------------------------------| +| **Core Operations** | `10,000` requests per minute | User login, create/delete user, create/join group (cumulative) | +| **Standard Operations** | `20,000` requests per minute | All other operations (cumulative) | + +## What Happens When the Rate Limit is Reached? + +The request isn't processed and a response is sent containing a `429` response code. Along with the response code, there will be a couple of headers sent which specify the time in seconds that you must wait before you can try the request again. + +``` +Retry-After: 15 +X-Rate-Limit-Reset: 1625143246 +``` + +## Is There an Endpoint That Returns Rate Limits? + +No, CometChat does not provide a dedicated rate-limit endpoint. + +However, the following response headers are included with every API response, which you can use to confirm the app's current rate limit and monitor the number of requests remaining in the current minute: + +``` +X-Rate-Limit: 700 +X-Rate-Limit-Remaining: 699 +``` + + + + - Monitor `X-Rate-Limit-Remaining` headers to proactively manage your request volume + - Implement exponential backoff when you receive a `429` response + - Use the `Retry-After` header value to determine when to retry + - Batch operations where possible to reduce the total number of API calls + - Cache responses locally to avoid redundant requests + + + - **Receiving 429 errors frequently:** Review your request patterns and consider batching or caching + - **Rate limit seems too low:** Contact CometChat support to discuss adjustments based on your plan and use case + - **Inconsistent rate limit headers:** Ensure you're reading headers from the correct response object in your HTTP client + + + +## Next Steps + + + + Review the fundamental building blocks of CometChat + + + Initialize CometChat and authenticate users in your app + + diff --git a/sdk/react-native/reactions.mdx b/sdk/react-native/reactions.mdx index 706fbcecc..49fdfb990 100644 --- a/sdk/react-native/reactions.mdx +++ b/sdk/react-native/reactions.mdx @@ -1,8 +1,23 @@ --- title: "Reactions" +description: "Add, remove, and manage message reactions in real-time using the CometChat React Native SDK." --- + +**Quick Reference** - Add and remove reactions: +```javascript +// Add a reaction +await CometChat.addReaction("MESSAGE_ID", "😊"); + +// Remove a reaction +await CometChat.removeReaction("MESSAGE_ID", "😊"); +``` + + + +Available via: [SDK](/sdk/react-native/reactions) | [REST API](/rest-api/messages/add-reaction) | [UI Kits](/ui-kit/react-native/core-features#reactions) + Enhance user engagement in your chat application with message reactions. Users can express their emotions using reactions to messages. This feature allows users to add or remove reactions, and to fetch all reactions on a message. You can also listen to reaction events in real-time. Let's see how to work with reactions in CometChat's SDK. @@ -43,6 +58,62 @@ CometChat.addReaction(messageId, emoji) + +**On Success** — `addReaction()` returns the updated message object with the reaction added: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "text": "Message for Reactions", + "reactions": [ + { + "reaction": "😊", + "count": 1, + "reactedByMe": true + } + ] + }, + "text": "Message for Reactions", + "id": "25327", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1772004288, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1772005334, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1772006757, + "deliveredAt": 1772006757, + "readAt": 1772006757, + "updatedAt": 1772006757 +} +``` + + You can react on text message, media message and custom message @@ -86,14 +157,63 @@ CometChat.removeReaction(messageId, emoji) + +**On Success** — `removeReaction()` returns the updated message object with the reaction removed: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "text": "Message for Reactions" + }, + "text": "Message for Reactions", + "id": "25327", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1772004288, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1772005334, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1772006757, + "deliveredAt": 1772006757, + "readAt": 1772006757, + "updatedAt": 1772006757 +} +``` + + ## Fetch Reactions for a Message -To get all reactions for a specific message, first create a `ReactionRequest` using `ReactionRequestBuilder`. You can specify the number of reactions to fetch with `setLimit` with max limit 100. For this, you will require the ID of the message. This ID needs to be passed to the `setMessageId()` method of the builder class. The `setReaction()` will allow you to fetch details for specific reaction or emoji. +To get all reactions for a specific message, first create a `ReactionsRequest` using `ReactionsRequestBuilder`. You can specify the number of reactions to fetch with `setLimit` with max limit 100. For this, you will require the ID of the message. This ID needs to be passed to the `setMessageId()` method of the builder class. The `setReaction()` will allow you to fetch details for specific reaction or emoji. | Setting | Description | | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `setMessageId(value)` | Specifies the unique identifier of the message for which you want to fetch reactions. This parameter is mandatory as it tells the SDK which message's reactions are being requested. | -| `setReaction(value)` | Filters the reactions fetched by the specified reaction type (e.g., "😊", "😂", "👍"). When set, this method will cause the `ReactionRequest` to only retrieve details of the provided reaction for the given message. | +| `setReaction(value)` | Filters the reactions fetched by the specified reaction type (e.g., "😊", "😂", "👍"). When set, this method will cause the `ReactionsRequest` to only retrieve details of the provided reaction for the given message. | ## Fetch Next @@ -105,16 +225,16 @@ The `fetchNext()` method fetches the next set of reactions for the message. let limit = 10; let messageId = 1; -let reactionRequest = new CometChat.ReactionRequestBuilder() +let reactionsRequest = new CometChat.ReactionsRequestBuilder() .setMessageId(messageId) .setLimit(limit) .build(); -reactionRequest.fetchNext().then( - messages => { - console.log("list fetched:", messages); +reactionsRequest.fetchNext().then( + reactions => { + console.log("list fetched:", reactions); }, - error => {a + error => { console.log('list fetching failed with error:', error); }, ); @@ -127,14 +247,14 @@ reactionRequest.fetchNext().then( let limit:number = 10; let messageId:number = 1; -let reactionRequest = new CometChat.ReactionRequestBuilder() +let reactionsRequest = new CometChat.ReactionsRequestBuilder() .setMessageId(messageId) .setLimit(limit) .build(); -reactionRequest.fetchNext().then( - (messages: MessageReaction[]) => { - console.log("list fetched:", messages); +reactionsRequest.fetchNext().then( + (reactions: CometChat.MessageReaction[]) => { + console.log("list fetched:", reactions); }, (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); @@ -156,16 +276,16 @@ The `fetchPrevious()` method fetches the previous set of reactions for the messa let limit = 10; let messageId = 1; -let reactionRequest = new CometChat.ReactionRequestBuilder() +let reactionsRequest = new CometChat.ReactionsRequestBuilder() .setMessageId(messageId) .setLimit(limit) .build(); -reactionRequest.fetchPrevious().then( - messages => { - console.log("list fetched:", messages); +reactionsRequest.fetchPrevious().then( + reactions => { + console.log("list fetched:", reactions); }, - error => {a + error => { console.log('list fetching failed with error:', error); }, ); @@ -178,14 +298,14 @@ reactionRequest.fetchPrevious().then( let limit:number = 10; let messageId:number = 1; -let reactionRequest = new CometChat.ReactionRequestBuilder() +let reactionsRequest = new CometChat.ReactionsRequestBuilder() .setMessageId(messageId) .setLimit(limit) .build(); -reactionRequest.fetchPrevious().then( - (messages: MessageReaction[]) => { - console.log("list fetched:", messages); +reactionsRequest.fetchPrevious().then( + (reactions: CometChat.MessageReaction[]) => { + console.log("list fetched:", reactions); }, (error: CometChat.CometChatException) => { console.log('list fetching failed with error:', error); @@ -197,6 +317,34 @@ reactionRequest.fetchPrevious().then( + +**On Success** — `fetchNext()` or `fetchPrevious()` returns an array of `MessageReaction` objects: +```json +[ + { + "id": "20014", + "messageId": "25327", + "reaction": "❤️", + "uid": "cometchat-uid-7", + "reactedAt": 1772007024, + "reactedBy": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1772007237, + "role": "default", + "status": "online" + } + } + // ... more reactions up to the specified limit +] +``` + + + ## Real-time Reaction Events Keep the chat interactive with real-time updates for reactions. Register a listener for these events and make your UI responsive. @@ -236,6 +384,58 @@ CometChat.addMessageListener(listenerID, { + +**On Event** — `onMessageReactionAdded` returns the reaction event data: +```json +{ + "parentMessageId": null, + "reaction": { + "id": "20013", + "messageId": "25327", + "reaction": "❤️", + "uid": "cometchat-uid-7", + "reactedAt": 1772006766, + "reactedBy": { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1772005334 + } + }, + "receiverId": "cometchat-uid-6", + "receiverType": "user", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7" +} +``` + +**On Event** — `onMessageReactionRemoved` returns the reaction event data: +```json +{ + "parentMessageId": null, + "reaction": { + "id": "20013", + "messageId": "25327", + "reaction": "❤️", + "uid": "cometchat-uid-7", + "reactedAt": 1772006766, + "reactedBy": { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1772005334 + } + }, + "receiverId": "cometchat-uid-6", + "receiverType": "user", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7" +} +``` + + ## Removing a Reaction Listener To stop listening for reaction events, remove the listener as follows: @@ -261,6 +461,10 @@ CometChat.removeMessageReactionListener(listenerID); + +Always remove your reaction listeners when they are no longer needed — for example, when a component unmounts or a screen is navigated away from. Failing to do so can cause memory leaks and unexpected behavior from stale listeners. Use `CometChat.removeMessageListener("LISTENER_ID")` in your cleanup logic (e.g., `useEffect` return function or `componentWillUnmount`). + + ## Get Reactions List To retrieve the list of reactions reacted on particular message, you can use the `message.getReactions()` method. This method will return an array containing the reactions, or an empty array if no one reacted on the message. @@ -282,6 +486,19 @@ message.getReactions() + +**On Success** — `getReactions()` returns an array of reaction counts: +```json +[ + { + "reaction": "❤️", + "count": 1, + "reactedByMe": true + } +] +``` + + ## Check if Logged-in User has Reacted on Message To check if the logged-in user has reacted on a particular message or not, You can use the `getReactedByMe()` method on any `ReactionCount` object instance. This method will return a boolean value, `true` if the logged-in user has reacted on that message, otherwise `false`. @@ -291,7 +508,7 @@ To check if the logged-in user has reacted on a particular message or not, You c ```javascript let reactions = message.getReactions(); reactions.forEach((reaction) => { -reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false +reaction.getReactedByMe(); //Returns true if logged-in user reacted on that message, otherwise false }) ``` @@ -301,7 +518,7 @@ reaction.getReactedByMe(); //Return true is logged-in user reacted on that messa ```typescript let reactions:CometChat.ReactionCount[] = message.getReactions(); reactions.forEach((reaction:CometChat.ReactionCount) => { -reaction.getReactedByMe(); //Return true is logged-in user reacted on that message, otherwise false +reaction.getReactedByMe(); //Returns true if logged-in user reacted on that message, otherwise false }) ``` @@ -359,3 +576,81 @@ action + + +**On Success (REACTION_ADDED)** — `updateMessageWithReactionInfo()` returns the updated message. Calling `getReactions()` on it shows: +```json +[ + { + "reactedByMe": false, + "reaction": "👍", + "count": 1 + } +] +``` + +**On Success (REACTION_REMOVED)** — When the last reaction is removed, `getReactions()` returns an empty array: +```json +[] +``` + + + +## Best Practices + + + + Always use unique, descriptive listener IDs (e.g., `"ChatScreen_ReactionListener"`) to avoid conflicts with other listeners in your app. This makes it easier to manage and remove specific listeners when needed. + + + Remove reaction listeners in your component's cleanup phase (`useEffect` return function or `componentWillUnmount`). Orphaned listeners can lead to memory leaks and unexpected UI updates on unmounted components. + + + When you receive a real-time reaction event, always call `updateMessageWithReactionInfo()` to keep your local message state in sync. This avoids stale reaction counts and ensures the UI reflects the latest state. + + + Wrap `addReaction` and `removeReaction` calls in proper error handling. Network issues or invalid message IDs can cause failures — show appropriate feedback to the user rather than silently failing. + + + When fetching reactions for messages with many reactions, use `fetchNext()` with a reasonable `setLimit()` value. Avoid fetching all reactions at once to keep performance smooth, especially on lower-end devices. + + + +## Troubleshooting + + + + Verify that the `messageId` is valid and the user is logged in. Check the error callback for details — common causes include invalid message IDs, network connectivity issues, or the user not being a participant in the conversation. + + + Ensure you have registered the message listener with `CometChat.addMessageListener()` before the reaction event occurs. Also confirm that the listener ID is unique and hasn't been accidentally removed or overwritten by another listener registration. + + + After receiving a real-time reaction event, you must call `CometChat.CometChatHelper.updateMessageWithReactionInfo()` to update the message object. Simply receiving the event does not automatically update the `BaseMessage` instance — you need to explicitly apply the update and re-render. + + + Make sure you are calling `getReactedByMe()` on the `ReactionCount` objects returned by `message.getReactions()`, not on the raw reaction event data. Also verify that the logged-in user is the same user who added the reaction. + + + Confirm that the `messageId` passed to `ReactionsRequestBuilder.setMessageId()` is correct and that the message actually has reactions. If using `setReaction()` to filter by a specific emoji, ensure the emoji string matches exactly (including any variation selectors). + + + +## Next Steps + +Explore related features to build a richer messaging experience: + + + + Learn how to send text, media, and custom messages to users and groups. + + + Set up real-time message listeners and fetch message history. + + + Tag users in messages to notify and engage them directly. + + + Send rich, interactive messages with forms, cards, and custom elements. + + \ No newline at end of file diff --git a/sdk/react-native/real-time-listeners.mdx b/sdk/react-native/real-time-listeners.mdx index ee34d9b64..e02846e22 100644 --- a/sdk/react-native/real-time-listeners.mdx +++ b/sdk/react-native/real-time-listeners.mdx @@ -1,8 +1,24 @@ --- title: "All Real Time Listeners" +description: "Learn how to register and manage all real-time listeners in the CometChat React Native SDK, including User, Group, Message, and Call listeners." --- - + +**Quick Reference** +```javascript +// Register listeners +CometChat.addUserListener("id", new CometChat.UserListener({ ... })); +CometChat.addGroupListener("id", new CometChat.GroupListener({ ... })); +CometChat.addMessageListener("id", new CometChat.MessageListener({ ... })); +CometChat.addCallListener("id", new CometChat.CallListener({ ... })); + +// Remove listeners +CometChat.removeUserListener("id"); +CometChat.removeGroupListener("id"); +CometChat.removeMessageListener("id"); +CometChat.removeCallListener("id"); +``` + CometChat provides 4 listeners viz. @@ -11,6 +27,10 @@ CometChat provides 4 listeners viz. 3. [Message Listener](#message-listener) 4. [Call Listener](#call-listener) + +Always remove all listeners when the component unmounts to prevent memory leaks. Ensure each listener has a unique ID — using duplicate IDs can lead to unexpected behavior and loss of events. + + ## User Listener The `UserListener` class provides you with live events related to users. Below are the callback methods provided by the `UserListener` class. @@ -95,7 +115,7 @@ The `GroupListener` class provides you with all the real-time events related to | **onGroupMemberLeft(action: CometChat.Action, leftUser: CometChat.User, leftGroup: CometChat.Group)** | This method is triggered when a user who was a member of any group leaves the group. All the members of the group receive this event. | | **onGroupMemberKicked(action: CometChat.Action, kickedUser: CometChat.User, kickedBy: CometChat.User, kickedFrom: CometChat.Group)** | This method is triggered when a user is kicked from a group. All the members including the user receive this event | | **onGroupMemberBanned(action: CometChat.Action, bannedUser: CometChat.User, bannedBy: CometChat.User, bannedFrom: CometChat.Group)** | This method is triggered when a user is banned from a group. All the members including the user receive this event | -| **onGroupMemberUnbanned(action: CometChat.Action, unbannedUser: CometChat.User, unbannedBy: CometChat.User, unbannedFrom: CometChat.Group)** | This method is triggered when a user is banned from a group. All the members of the group receive this event. | +| **onGroupMemberUnbanned(action: CometChat.Action, unbannedUser: CometChat.User, unbannedBy: CometChat.User, unbannedFrom: CometChat.Group)** | This method is triggered when a user is unbanned from a group. All the members of the group receive this event. | | **onGroupMemberScopeChanged(action: CometChat.Action, changedUser: CometChat.User, newScope: string, oldScope: string, changedGroup: CometChat.Group)** | This method is triggered when the scope of any Group Member has been changed. All the members that are a part of that group receive this event | | **onMemberAddedToGroup(action: CometChat.Action, userAdded: CometChat.User, addedBy: CometChat.User, addedTo: CometChat.Group)** | This method is triggered when a user is added to any group. All the members including the user himself receive this event. | @@ -306,7 +326,7 @@ The `MessageListener` class provides you with live events related to messages. B | **onInteractionGoalCompleted(receipt: CometChat.InteractionReceipt)** | This event is triggered when an interaction Goal is achieved. | | **onTransientMessageReceived(receipt: CometChat.TransientMessage)** | This event is triggered when a Transient Message is received. | | **onMessageReactionAdded(receipt: CometChat.ReactionEvent)** | This event is triggered when a reaction is added to a message in a user/group conversation. | -| **onMessageReactionRemoved(receipt: CometChat.ReactionEvent)** | This event is triggered when a reaction is remove from a message in a user/group conversation. | +| **onMessageReactionRemoved(receipt: CometChat.ReactionEvent)** | This event is triggered when a reaction is removed from a message in a user/group conversation. | To add the `MessageListener`, you need to use the `addMessageListener()` method provided by the `CometChat` class. @@ -524,3 +544,38 @@ CometChat.removeCallListener(listenerID); + + + +- Register listeners as early as possible in your app lifecycle (e.g., after successful login) to avoid missing events +- Use unique, descriptive listener IDs (e.g., `"CHAT_SCREEN_MESSAGE_LISTENER"`) to make debugging easier +- Always remove listeners when the component unmounts or the user logs out +- Avoid registering the same listener ID multiple times — this overwrites the previous listener silently +- For React Native, use `useEffect` cleanup functions to handle listener removal automatically + + + +- **Events not firing**: Ensure the listener is registered with a unique ID and that you're handling the correct callback method for the event type. +- **Duplicate events**: Check that you're not registering the same listener multiple times without removing the previous one first. +- **Events stop after navigation**: If you remove listeners on screen unmount, re-register them when the screen mounts again. +- **Missing group events**: Group listeners only fire for groups the logged-in user is a member of. Verify group membership. +- **Call events not received**: Ensure the CometChat Calling SDK is properly initialized alongside the Chat SDK. + + + +## Next Steps + + + +Track when users come online or go offline + + +Handle incoming messages in real time + + +Show when users are typing + + +Implement voice and video calling + + diff --git a/sdk/react-native/receive-messages.mdx b/sdk/react-native/receive-messages.mdx index b6aff913f..b85820db6 100644 --- a/sdk/react-native/receive-messages.mdx +++ b/sdk/react-native/receive-messages.mdx @@ -1,98 +1,389 @@ --- title: "Receive A Message" +description: "Receive real-time messages, fetch missed and unread messages, retrieve message history, and get unread message counts using the CometChat React Native SDK." --- + +**Quick Reference** - Listen for incoming messages: +```javascript +CometChat.addMessageListener("listener-id", new CometChat.MessageListener({ + onTextMessageReceived: (msg) => console.log("Text:", msg), + onMediaMessageReceived: (msg) => console.log("Media:", msg), + onCustomMessageReceived: (msg) => console.log("Custom:", msg), +})); + +// Don't forget to remove the listener when done +CometChat.removeMessageListener("listener-id"); +``` + + + +Available via: [SDK](/sdk/react-native/receive-messages) | [REST API](/rest-api/messages/list-messages) | [UI Kits](/ui-kit/react-native/core-features#instant-messaging) + Receiving messages with CometChat has two parts: -1. Adding a listener to receive [real-time messages](/sdk/react-native/receive-messages#real-time-messages) when your app is running -2. Calling a method to retrieve [missed messages](/sdk/react-native/receive-messages#missed-messages) when your app was not running +1. Adding a listener to receive [real-time messages](#real-time-messages) when your app is running +2. Calling a method to retrieve [missed messages](#missed-messages) when your app was not running ## Real-Time Messages *In other words, as a recipient, how do I receive messages when my app is running?* -To receive real-time incoming messages, you need to register the MessageListener wherever you wish to receive the incoming messages. You can use the addMessageListener() method to do so. +To receive real-time incoming messages, you need to register the MessageListener wherever you wish to receive the incoming messages. You can use the `addMessageListener()` method to do so. - -```javascript -let listenerID = "UNIQUE_LISTENER_ID"; + + ```javascript + let listenerID = "UNIQUE_LISTENER_ID"; + + CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onTextMessageReceived: (textMessage) => { + console.log("Text message received successfully", textMessage); + }, + onMediaMessageReceived: (mediaMessage) => { + console.log("Media message received successfully", mediaMessage); + }, + onCustomMessageReceived: (customMessage) => { + console.log("Custom message received successfully", customMessage); + }, + }) + ); + ``` + + + ```typescript + let listenerID: string = "UNIQUE_LISTENER_ID"; + + CometChat.addMessageListener( + listenerID, + new CometChat.MessageListener({ + onTextMessageReceived: (textMessage: CometChat.TextMessage) => { + console.log("Text message received successfully", textMessage); + }, + onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { + console.log("Media message received successfully", mediaMessage); + }, + onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { + console.log("Custom message received successfully", customMessage); + }, + }) + ); + ``` + + -CometChat.addMessageListener( - listenerID, - new CometChat.MessageListener({ - onTextMessageReceived: (textMessage) => { - console.log("Text message received successfully", textMessage); +| Parameter | Description | +| -------------- | --------------------------------------------- | +| **listenerId** | An ID that uniquely identifies that listener. | + + +**onTextMessageReceived** — `console.log("Text message received successfully", textMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771386383, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386392, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } }, - onMediaMessageReceived: (mediaMessage) => { - console.log("Media message received successfully", mediaMessage); + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } }, - onCustomMessageReceived: (customMessage) => { - console.log("Custom message received successfully", customMessage); + "moderation": { + "status": "approved" }, - }) -); + "resource": "REACT_NATIVE-4_0_14-e00a3397-8084-4596-9425-35f7e61a1111-1771332420737", + "text": "Hello" + }, + "text": "Hello", + "id": "25195", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386392, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771386383, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771386431, + "updatedAt": 1771386431, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} ``` - - - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; +**onMediaMessageReceived** — `console.log("Media message received successfully", mediaMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "attachments": [ + { + "extension": "jpg", + "mimeType": "image/jpeg", + "name": "photo.jpg", + "size": 142099, + "url": "https://data-in.cometchat.io/2748663902141719/media/1771386517_1811543964_565af45463f0170fda1720c8138a7761.jpg" + } + ], + "category": "message", + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771386436, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386507, + "name": "Nancy Grace", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-e00a3397-8084-4596-9425-35f7e61a1111-1771332420737", + "type": "image", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771386517_1811543964_565af45463f0170fda1720c8138a7761.jpg" + }, + "id": "25196", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386507, + "role": "default", + "status": "offline", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771386436, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771386517, + "updatedAt": 1771386517 +} +``` -CometChat.addMessageListener( - listenerID, - new CometChat.MessageListener({ - onTextMessageReceived: (textMessage: CometChat.TextMessage) => { - console.log("Text message received successfully", textMessage); +**onCustomMessageReceived** — `console.log("Custom message received successfully", customMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "test-custom", + "receiverType": "user", + "category": "custom", + "customData": { + "greeting": "Hello from custom message!", + "timestamp": 1771386646780 + }, + "data": { + "customData": { + "greeting": "Hello from custom message!", + "timestamp": 1771386646780 + }, + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771386436, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386517, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } }, - onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => { - console.log("Media message received successfully", mediaMessage); + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } }, - onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => { - console.log("Custom message received successfully", customMessage); + "moderation": { + "status": "approved" }, - }) -); + "resource": "REACT_NATIVE-4_0_14-e00a3397-8084-4596-9425-35f7e61a1111-1771332420737", + "text": "Sent a custom message" + }, + "id": "25197", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771386517, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771386436, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771386648, + "updatedAt": 1771386648, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} ``` + - - - - -| Parameter | Description | | -| -------------- | --------------------------------------------- | - | -| **listenerId** | An ID that uniquely identifies that listener. | | - -We recommend you remove the listener once you don't want to receive a message for particular listener. You can remove the listener in componentWillUnmount() method. + +**Listener Cleanup:** Always remove the listener once you don't need to receive messages for a particular listener. Remove the listener in `componentWillUnmount()` or the cleanup function of a `useEffect` to prevent memory leaks. + - -```javascript -var listenerID = "UNIQUE_LISTENER_ID"; - -CometChat.removeMessageListener(listenerID); -``` - - - - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; - -CometChat.removeMessageListener(listenerID); -``` - - - + + ```javascript + var listenerID = "UNIQUE_LISTENER_ID"; + CometChat.removeMessageListener(listenerID); + ``` + + + ```typescript + let listenerID: string = "UNIQUE_LISTENER_ID"; + CometChat.removeMessageListener(listenerID); + ``` + - As a sender, you will not receive your own message in a real-time message event. However, if a user is logged-in using multiple devices, they will receive an event for their own message in other devices. - ## Missed Messages @@ -101,229 +392,645 @@ As a sender, you will not receive your own message in a real-time message event. For most use cases, you will need to add functionality to load missed messages. If you're building an on-demand or live streaming app, you may choose to skip this and fetch message history instead. -Using the same `MessagesRequest` class and the filters provided by the `MessagesRequestBuilder` class, you can fetch the message that we sent to the logged-in user but were not delivered to him as he was offline. For this, you will require the Id of the last message received. You can either maintain it at your end or use the `getLastDeliveredMessageId()` method provided by the CometChat class. This Id needs to be passed to the `setMessageId()` method of the builder class. +Using the same `MessagesRequest` class and the filters provided by the `MessagesRequestBuilder` class, you can fetch the messages that were sent to the logged-in user but were not delivered to them as they were offline. For this, you will require the ID of the last message received. You can either maintain it at your end or use the `getLastDeliveredMessageId()` method provided by the CometChat class. This ID needs to be passed to the `setMessageId()` method of the builder class. -Now using the `fetchNext()` method, you can fetch all the messages that were sent to the user when he/she was offline. +Now using the `fetchNext()` method, you can fetch all the messages that were sent to the user when they were offline. -Calling the `fetchNext()` method on the same object repeatedly allows you to fetch all the offline messages for the logged in user. +Calling the `fetchNext()` method on the same object repeatedly allows you to fetch all the offline messages for the logged-in user. ### For a Particular One-on-one Conversation - -```javascript -let UID = "UID"; -let limit = 30; -let latestId = await CometChat.getLastDeliveredMessageId(); - -var messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setMessageId(latestId) - .setLimit(limit) - .build(); - -messagesRequest.fetchNext().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` + + ```javascript + let UID = "UID"; + let limit = 30; + let latestId = await CometChat.getLastDeliveredMessageId(); - - - -```typescript -let UID: string = "UID", - limit: number = 30, - latestId: number = await CometChat.getLastDeliveredMessageId(), - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() + var messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setMessageId(latestId) .setLimit(limit) .build(); -messagesRequest.fetchNext().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + messagesRequest.fetchNext().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let UID: string = "UID", + limit: number = 30, + latestId: number = await CometChat.getLastDeliveredMessageId(), + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setMessageId(latestId) + .setLimit(limit) + .build(); + + messagesRequest.fetchNext().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771388888, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Missed Message" + }, + "text": "Missed Message", + "id": "25211", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771388888, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771388912, + "updatedAt": 1771388912, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For a Particular Group - -```javascript -let GUID = "GUID"; -let limit = 30; -let latestId = await CometChat.getLastDeliveredMessageId(); - -var messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setMessageId(latestId) - .setLimit(limit) - .build(); - -messagesRequest.fetchNext().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - + + ```javascript + let GUID = "GUID"; + let limit = 30; + let latestId = await CometChat.getLastDeliveredMessageId(); - -```typescript -let GUID: string = "GUID", - limit: number = 30, - latestId: number = await CometChat.getLastDeliveredMessageId(), - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() + var messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setMessageId(latestId) .setLimit(limit) .build(); -messagesRequest.fetchNext().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + messagesRequest.fetchNext().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let GUID: string = "GUID", + limit: number = 30, + latestId: number = await CometChat.getLastDeliveredMessageId(), + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setMessageId(latestId) + .setLimit(limit) + .build(); + + messagesRequest.fetchNext().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1749203133, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Group Missed" + }, + "text": "Group Missed", + "id": "25215", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1749203133, + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771389682, + "updatedAt": 1771389682, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ## Unread Messages *In other words, as a logged-in user, how do I fetch the messages I've not read?* -Using the `MessagesRequest` class described above, you can fetch the unread messages for the logged in user. In order to achieve this, you need to set the `unread` variable in the builder to true using the `setUnread()` method so that only the unread messages are fetched. +Using the `MessagesRequest` class described above, you can fetch the unread messages for the logged-in user. In order to achieve this, you need to set the `unread` variable in the builder to true using the `setUnread()` method so that only the unread messages are fetched. ### For a Particular One-on-one Conversation - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() + + ```javascript + let UID = "UID"; + let limit = 30; + let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setUnread(true) .setLimit(limit) .build(); -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setUnread(true) + .setLimit(limit) + .build(); + + messagesRequest.fetchPrevious().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771389781, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Unread Message" + }, + "text": "Unread Message", + "id": "25216", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771389781, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771390060, + "deliveredAt": 1771390061, + "updatedAt": 1771390061, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For a Particular Group - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setUnread(true) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() + + ```javascript + let GUID = "GUID"; + let limit = 30; + let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setUnread(true) .setLimit(limit) .build(); -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setUnread(true) + .setLimit(limit) + .build(); + + messagesRequest.fetchPrevious().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1749203133, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Unread Group Message" + }, + "text": "Unread Group Message", + "id": "25217", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1749203133, + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771390129, + "updatedAt": 1771390129, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + -Base Message - -The list of messages received is in the form of objects of `BaseMessage` class. A BaseMessage can either be an object of the `TextMessage`, `MediaMessage`, `CustomMessage`, `Action` or `Call` class. You can use the `instanceOf` operator to check the type of object. - +**Base Message:** The list of messages received is in the form of objects of `BaseMessage` class. A BaseMessage can either be an object of the `TextMessage`, `MediaMessage`, `CustomMessage`, `Action` or `Call` class. You can use the `instanceOf` operator to check the type of object. ## Message History @@ -332,229 +1039,828 @@ The list of messages received is in the form of objects of `BaseMessage` class. ### For a Particular One-on-one Conversation -Using the `MessagesRequest` class and the filters for the `MessagesRequestBuilder` class as shown in the below code snippet, you can fetch the entire conversation between the logged in user and any particular user. For this use case, it is mandatory to set the UID parameter using the `setUID()` method of the builder. This UID is the unique id of the user for which the conversation needs to be fetched. +Using the `MessagesRequest` class and the filters for the `MessagesRequestBuilder` class as shown in the below code snippet, you can fetch the entire conversation between the logged-in user and any particular user. For this use case, it is mandatory to set the UID parameter using the `setUID()` method of the builder. This UID is the unique ID of the user for which the conversation needs to be fetched. - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - + + ```javascript + let UID = "UID"; + let limit = 30; + let messagesRequest = new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .build(); - -```typescript -let UID: string = "UID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(limit).build(); + messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let UID: string = "UID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(limit).build(); + + messagesRequest.fetchPrevious().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); +Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch the entire conversation between the logged-in user and the specified user. This can be implemented with upward scrolling to display the entire conversation. + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771389781, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Historic 1-1" + }, + "text": "Historic 1-1", + "id": "25220", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771389781, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771390691, + "updatedAt": 1771390691, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771389781, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Historic Msg 2 One to One" + }, + "text": "Historic Msg 2 One to One", + "id": "25221", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771389781, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771390711, + "updatedAt": 1771390711, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - - -Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch the entire conversation between the logged in user and the specified user. This can be implemented with upward scrolling to display the entire conversation. +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For a Particular Group Using the `MessagesRequest` class and the filters for the `MessagesRequestBuilder` class as shown in the below code snippet, you can fetch the entire conversation for any group provided you have joined the group. For this use case, it is mandatory to set the GUID parameter using the `setGUID()` method of the builder. This GUID is the unique identifier of the Group for which the messages are to be fetched. - -```javascript -let GUID = "GUID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() + + ```javascript + let GUID = "GUID"; + let limit = 30; + let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) .build(); -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); + messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let GUID: string = "GUID", + limit: number = 30, + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .build(); + + messagesRequest.fetchPrevious().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + +Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch the entire conversation for the group. This can be implemented with upward scrolling to display the entire conversation. + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1749203133, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Historic Message 1" + }, + "text": "Historic Message 1", + "id": "25218", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1749203133, + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771390631, + "updatedAt": 1771390631, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1749203133, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "Historic Message 2" + }, + "text": "Historic Message 2", + "id": "25219", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771388895, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1749203133, + "onlineMembersCount": 1, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771390637, + "updatedAt": 1771390637, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - - -Calling the `fetchPrevious()` method on the same object repeatedly allows you to fetch the entire conversation for the group. This can be implemented with upward scrolling to display the entire conversation. +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ## Search Messages -In other words, as a logged-in user, how do I search a message? +*In other words, as a logged-in user, how do I search a message?* -In order to do this, you can use the `setSearchKeyword()` method. This method accepts string as input. When set, the SDK will fetch messages which match the `searchKeyword`. +In order to do this, you can use the `setSearchKeyword()` method. This method accepts a string as input. When set, the SDK will fetch messages which match the `searchKeyword`. - By default, the searchKey is searched only in message text. However, if you enable `Conversation & Advanced Search`, the searchKey will be searched in message text, file name, mentions & mime type of the file. -The `Conversation & Advanced Search` is only available in `Advanced` & `Custom` [plans](https://www.cometchat.com/pricing). If you're already on one of these plans, please enable the `Conversation & Advanced Search` from [CometChat Dashboard](https://app.cometchat.com) (Open your app, navigate to Chats -> Settings -> General Configuration) - +The `Conversation & Advanced Search` is only available in `Advanced` & `Custom` [plans](https://www.cometchat.com/pricing). If you're already on one of these plans, please enable the `Conversation & Advanced Search` from [CometChat Dashboard](https://app.cometchat.com) (Open your app, navigate to Chats -> Settings -> General Configuration). -| Feature | Basic Search | Advance Search | -| ---------------- | ------------ | -------------- | -| Text search | ✅ | ✅ | -| File name search | ❌ | ✅ | -| Mentions search | ❌ | ✅ | -| Mime type search | ❌ | ✅ | +| Feature | Basic Search | Advanced Search | +| ---------------- | ------------ | --------------- | +| Text search | ✅ | ✅ | +| File name search | ❌ | ✅ | +| Mentions search | ❌ | ✅ | +| Mime type search | ❌ | ✅ | ### For a Particular One-on-one Conversation - -```javascript -let UID = "UID"; -let limit = 30; -let searchKeyword = "Hello"; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - -```typescript -let UID: string = "UID", - limit: number = 30, - searchKeyword: string = "Hello", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() + + ```javascript + let UID = "UID"; + let limit = 30; + let searchKeyword = "Hello"; + let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) .setSearchKeyword(searchKeyword) .build(); -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let UID: string = "UID", + limit: number = 30, + searchKeyword: string = "Hello", + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setUID(UID) + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); + + messagesRequest.fetchPrevious().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771391157, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771391162, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "xq7SearchTest" + }, + "text": "xq7SearchTest", + "id": "25224", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771391162, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771391157, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771392432, + "deliveredAt": 1771392432, + "readAt": 1771392432, + "updatedAt": 1771392432, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For a Particular Group - -```javascript -let GUID = "GUID"; -let limit = 30; -let searchKeyword = "Hello"; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setGUID(GUID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); - -messagesRequest.fetchPrevious().then( - (messages) => { - console.log("Message list fetched:", messages); - }, - (error) => { - console.log("Message fetching failed with error:", error); - } -); -``` - - - - -```typescript -let GUID: string = "GUID", - limit: number = 30, - searchKeyword: string = "Hello", - messagesRequest: CometChat.MessagesRequest = - new CometChat.MessagesRequestBuilder() + + ```javascript + let GUID = "GUID"; + let limit = 30; + let searchKeyword = "Hello"; + let messagesRequest = new CometChat.MessagesRequestBuilder() .setGUID(GUID) .setLimit(limit) .setSearchKeyword(searchKeyword) .build(); -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); + messagesRequest.fetchPrevious().then( + (messages) => { + console.log("Message list fetched:", messages); + }, + (error) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + ```typescript + let GUID: string = "GUID", + limit: number = 30, + searchKeyword: string = "Hello", + messagesRequest: CometChat.MessagesRequest = + new CometChat.MessagesRequestBuilder() + .setGUID(GUID) + .setLimit(limit) + .setSearchKeyword(searchKeyword) + .build(); + + messagesRequest.fetchPrevious().then( + (messages: CometChat.BaseMessage[]) => { + console.log("Message list fetched:", messages); + }, + (error: CometChat.CometChatException) => { + console.log("Message fetching failed with error:", error); + } + ); + ``` + + + + +**On Success** — `console.log("Message list fetched:", messages)` returns: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1749203133, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 2, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771391162, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-2f7dd257-8576-4279-9ac5-24a0b83ceb5d-1771388893612", + "text": "xq8SearchTest" + }, + "text": "xq8SearchTest", + "id": "25225", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771391162, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1749203133, + "onlineMembersCount": 2, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771392513, + "updatedAt": 1771392513, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } } -); +] ``` - - - +**On Failure** — `console.log("Message fetching failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ## Unread Message Count @@ -562,399 +1868,473 @@ messagesRequest.fetchPrevious().then( ### For a Particular One-on-one Conversation -*In other words, how do I find out the number of unread messages I have from a particular user?* +*How do I find out the number of unread messages I have from a particular user?* -In order to get the unread message count for a particular user, you can use the `getUnreadMessageCountForUser()`. +In order to get the unread message count for a particular user, you can use the `getUnreadMessageCountForUser()` method. This method has the below two variants: - -```javascript -CometChat.getUnreadMessageCountForUser(UID); -``` - - - - -```typescript -let UID: string = "UID"; -CometChat.getUnreadMessageCountForUser(UID); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForUser(UID); + ``` + + + ```typescript + let UID: string = "UID"; + CometChat.getUnreadMessageCountForUser(UID); + ``` + If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - -```javascript -CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); -``` - - - - -```typescript -let UID: string = "UID", - hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); + ``` + + + ```typescript + let UID: string = "UID", + hideMessagesFromBlockedUsers: boolean = true; + CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); + ``` + - -```javascript -let UID = "UID"; - -CometChat.getUnreadMessageCountForUser(UID).then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` - - + + ```javascript + let UID = "UID"; + + CometChat.getUnreadMessageCountForUser(UID).then( + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); + }, + (error) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + + ```typescript + let UID: string = "UID"; + + CometChat.getUnreadMessageCountForUser(UID).then( + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); + }, + (error: CometChat.CometChatException) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + - -```typescript -let UID: string = "UID"; +It will return an object which will contain the UID as the key and the unread message count as the value. -CometChat.getUnreadMessageCountForUser(UID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } -); + +**On Success** — `console.log("Unread message count fetched", unreadMessageCountObject)` returns: +```json +{ + "cometchat-uid-3": 2 +} ``` - - - - -It will return an object which will contain the UID as the key and the unread message count as the value. +**On Failure** — `console.log("Error in getting unread message count", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For a Particular Group Conversation -*In other words, how do I find out the number of unread messages I have in a single group?* +*How do I find out the number of unread messages I have in a single group?* -In order to get the unread message count for a particular group, you can use the `getUnreadMessageCountForGroup()`. +In order to get the unread message count for a particular group, you can use the `getUnreadMessageCountForGroup()` method. This method has the below two variants: - -```javascript -CometChat.getUnreadMessageCountForGroup(GUID); -``` - - - - -```typescript -let GUID: string = "GUID"; -CometChat.getUnreadMessageCountForGroup(GUID); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForGroup(GUID); + ``` + + + ```typescript + let GUID: string = "GUID"; + CometChat.getUnreadMessageCountForGroup(GUID); + ``` + -\`\` - If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - -```javascript -CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); -``` - - - - -```typescript -let GUID: string = "GUID", - hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); + ``` + + + ```typescript + let GUID: string = "GUID", + hideMessagesFromBlockedUsers: boolean = true; + CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); + ``` + - -```javascript -let GUID = "GUID"; - -CometChat.getUnreadMessageCountForGroup(GUID).then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` - - + + ```javascript + let GUID = "GUID"; + + CometChat.getUnreadMessageCountForGroup(GUID).then( + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); + }, + (error) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + + ```typescript + let GUID: string = "GUID"; + + CometChat.getUnreadMessageCountForGroup(GUID).then( + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); + }, + (error: CometChat.CometChatException) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + - -```typescript -let GUID: string = "GUID"; +It will return an object which will contain the GUID as the key and the unread message count as the value. -CometChat.getUnreadMessageCountForGroup(GUID).then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } -); + +**On Success** — `console.log("Unread message count fetched", unreadMessageCountObject)` returns: +```json +{ + "group_1748415903905": 3 +} ``` - - - - -It will return an object which will contain the GUID as the key and the unread message count as the value. +**On Failure** — `console.log("Error in getting unread message count", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For All One-on-one & Group Conversations -*In other words, how do I find out the number of unread messages for every one-on-one and group conversation?* +*How do I find out the number of unread messages for every one-on-one and group conversation?* In order to get all the unread message count combined i.e unread message counts for all the users and groups, you can use the `getUnreadMessageCount()` method. This method has two variants: - -```javascript -CometChat.getUnreadMessageCount(); -``` - - - - -```typescript -CometChat.getUnreadMessageCount(); -``` - - - + + ```javascript + CometChat.getUnreadMessageCount(); + ``` + + + ```typescript + CometChat.getUnreadMessageCount(); + ``` + If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - -```javascript -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` - - - - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` - - - + + ```javascript + CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); + ``` + + + ```typescript + let hideMessagesFromBlockedUsers: boolean = true; + CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); + ``` + - -```javascript -CometChat.getUnreadMessageCount().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` + + ```javascript + CometChat.getUnreadMessageCount().then( + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); + }, + (error) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + + ```typescript + CometChat.getUnreadMessageCount().then( + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); + }, + (error: CometChat.CometChatException) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + + +It returns an object having two keys: - +1. `users` - The value for this key holds another object that holds the UID as key and their corresponding unread message count as value. +2. `groups` - The value for this key holds another object that holds the GUID as key and their corresponding unread message count as value. - -```typescript -CometChat.getUnreadMessageCount().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); + +**On Success** — `console.log("Unread message count fetched", unreadMessageCountObject)` returns: +```json +{ + "users": { + "cometchat-uid-3": 2 }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); + "groups": { + "group_1748415903905": 2 } -); +} ``` - - - - -It returns an object having two keys: - -1. users - The value for this key holds another object that holds the UID as key and their corresponding unread message count as value. -2. groups - The value for this key holds another object that holds the GUID as key and their corresponding unread message count as value. +**On Failure** — `console.log("Error in getting unread message count", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For All One-on-one Conversations In order to fetch the unread message counts for just the users, you can use the `getUnreadMessageCountForAllUsers()` method. This method just like others has two variants: - -```javascript -CometChat.getUnreadMessageCountForAllUsers(); -``` - - - - -```typescript -CometChat.getUnreadMessageCountForAllUsers(); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForAllUsers(); + ``` + + + ```typescript + CometChat.getUnreadMessageCountForAllUsers(); + ``` + If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - -```javascript -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); -``` - - - - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); + ``` + + + ```typescript + let hideMessagesFromBlockedUsers: boolean = true; + CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); + ``` + - -```javascript -CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` + + ```javascript + CometChat.getUnreadMessageCountForAllUsers().then( + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); + }, + (error) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + + ```typescript + CometChat.getUnreadMessageCountForAllUsers().then( + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); + }, + (error: CometChat.CometChatException) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + - +It returns an object which will contain the UID as the key and the unread message count as the value. - -```typescript -CometChat.getUnreadMessageCountForAllUsers().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } -); + +**On Success** — `console.log("Unread message count fetched", unreadMessageCountObject)` returns: +```json +{ + "cometchat-uid-3": 2, + "cometchat-uid-4": 3 +} ``` - - - - -It returns an object which will contain the UID as the key and the unread message count as the value. +**On Failure** — `console.log("Error in getting unread message count", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + ### For All Group Conversations In order to fetch the unread message counts for just the groups, you can use the `getUnreadMessageCountForAllGroups()` method. This method just like others has two variants: - -```javascript -CometChat.getUnreadMessageCountForAllGroups(); -``` - - - - -```typescript -CometChat.getUnreadMessageCountForAllGroups(); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForAllGroups(); + ``` + + + ```typescript + CometChat.getUnreadMessageCountForAllGroups(); + ``` + If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: - -```javascript -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); -``` - - - - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); -``` - - - + + ```javascript + CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); + ``` + + + ```typescript + let hideMessagesFromBlockedUsers: boolean = true; + CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); + ``` + - -```javascript -CometChat.getUnreadMessageCountForAllGroups().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` + + ```javascript + CometChat.getUnreadMessageCountForAllGroups().then( + (unreadMessageCountObject) => { + console.log("Unread message count fetched", unreadMessageCountObject); + }, + (error) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + + ```typescript + CometChat.getUnreadMessageCountForAllGroups().then( + (unreadMessageCount: Object) => { + console.log("Unread message count fetched", unreadMessageCount); + }, + (error: CometChat.CometChatException) => { + console.log("Error in getting unread message count", error); + } + ); + ``` + + - +It returns an object which will contain the GUID as the key and the unread message count as the value. - -```typescript -CometChat.getUnreadMessageCountForAllGroups().then( - (unreadMessageCount: Object) => { - console.log("Unread message count fetched", unreadMessageCount); - }, - (error: CometChat.CometChatException) => { - console.log("Error in getting unread message count", error); - } -); + +**On Success** — `console.log("Unread message count fetched", unreadMessageCountObject)` returns: +```json +{ + "group_1748415903905": 2, + "group_1762515421478": 2, + "group_1762515423434": 5 +} ``` - - - - -It returns an object which will contain the GUID as the key and the unread message count as the value. +**On Failure** — `console.log("Error in getting unread message count", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in.", + "details": {} +} +``` + + + + + - Always remove message listeners when a component unmounts to prevent memory leaks + - Use unique, descriptive listener IDs (e.g., `"chat-screen-listener"`) to avoid conflicts + - Use `getLastDeliveredMessageId()` to efficiently fetch only missed messages + - Implement pagination with `fetchPrevious()` for message history to avoid loading too many messages at once + - Use `setUnread(true)` to fetch only unread messages when building notification badges + + + - **Not receiving messages:** Ensure the message listener is registered and the user is logged in + - **Duplicate messages:** Check that you're not adding the same listener ID multiple times + - **Missing messages after reconnect:** Use the missed messages pattern with `getLastDeliveredMessageId()` to catch up + - **Unread count not updating:** Ensure you're calling the unread count methods after marking messages as read + + + +## Next Steps + + + + Send text, media, and custom messages to users and groups + + + Track when messages are delivered and read + + + Show real-time typing status in conversations + + + Understand message categories, types, and hierarchy + + diff --git a/sdk/react-native/recording.mdx b/sdk/react-native/recording.mdx index ca7b2498d..234cf251a 100644 --- a/sdk/react-native/recording.mdx +++ b/sdk/react-native/recording.mdx @@ -1,18 +1,39 @@ --- title: "Recording (Beta)" +description: "Add call recording to your React Native app with start/stop controls, recording listeners, and automatic recording on call start." --- + +**Quick Reference** - Start and stop call recording: +```javascript +// Start recording +CometChatCalls.startRecording(); + +// Stop recording +CometChatCalls.stopRecording(); -This section will guide you to implement call recording feature for the voice and video calls. +// Or enable auto-recording via CallSettings +new CometChatCalls.CallSettingsBuilder() + .startRecordingOnCallStart(true) + .showRecordingButton(true) + .build(); +``` + -## Implementation + +**Available via:** SDK | UI Kits + -Once you have decided to implement [Default Calling](/sdk/react-native/default-call) or [Direct Calling](/sdk/react-native/direct-call) and followed the steps to implement them. Just few additional listeners and methods will help you quickly implement call recording in your app. +## Overview -You need to make changes in the `CometChatCalls.OngoingCallListener` constructor and add the required listeners for recording. Please make sure your callSettings is configured accordingly for [Default Calling](/sdk/react-native/default-call) or [Direct Calling](/sdk/react-native/direct-call). +This section guides you through implementing call recording for voice and video calls. -A basic example of how to make changes to implement recording for a direct call/ a default call: +Once you have decided to implement [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call) and followed the steps to implement them, a few additional listeners and methods will help you quickly implement call recording in your app. + +You need to make changes in the `CometChatCalls.OngoingCallListener` constructor and add the required listeners for recording. Please make sure your callSettings is configured accordingly for [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call). + +A basic example of how to make changes to implement recording: @@ -85,9 +106,48 @@ render(){ -## Settings for call recording + +**On Event** — `onRecordingStarted` returns information about the user who started the recording: + + + +**RecordingStartedBy Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user who started recording | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `recordId` | string | Unique identifier for this recording session | `"noujausedimwfhwl"` | +| `id` | string | Internal session participant ID | `"042d0440"` | +| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | +| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | +| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | -The `CallSettings` class allows you to customise the overall calling experience. The properties for the call/conference can be set using the `CallSettingsBuilder` class. This will eventually give you and object of the `CallSettings` class which you can pass to the `startSession()` method to start the call. + + + +**On Event** — `onRecordingStopped` returns information about the user who stopped the recording: + + + +**RecordingStoppedBy Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user who stopped recording | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `id` | string | Internal session participant ID | `"042d0440"` | +| `isLocalUser` | string | Whether this is the local user (as string) | `"true"` | +| `isVideoMuted` | string | Whether user's video is muted (as string) | `"true"` | +| `isAudioMuted` | string | Whether user's audio is muted (as string) | `"false"` | + + + +## Settings for Call Recording + +The `CallSettings` class allows you to customise the overall calling experience. The properties for the call/conference can be set using the `CallSettingsBuilder` class. This will eventually give you an object of the `CallSettings` class which you can pass to the `CometChatCalls.Component` to start the call. The options available for recording of calls are: @@ -155,3 +215,50 @@ Currently, the call recordings are available on the [CometChat Dashboard](https: + +## Best Practices + + + + The ongoing call component automatically displays a recording badge when recording starts — you don't need to build or control this UI. Use the `onRecordingStarted` and `onRecordingStopped` listeners if you need to track recording state in your app logic (e.g., logging or analytics). + + + If your app requires all calls to be recorded (e.g., for compliance or audit purposes), enable `startRecordingOnCallStart(true)` in your `CallSettingsBuilder` to ensure no calls are missed. + + + If you're using a custom layout (`enableDefaultLayout(false)`), track the recording state using `onRecordingStarted` and `onRecordingStopped` listeners to toggle your custom recording button's appearance. + + + +## Troubleshooting + + + + Ensure `showRecordingButton(true)` is set in your `CallSettingsBuilder`. The recording button is hidden by default (`false`). Also verify that `enableDefaultLayout(true)` is set, as the button is part of the default layout. + + + These listeners require JS SDK v3.0.8 or later. Verify your SDK version. Also ensure the listeners are registered in the `OngoingCallListener` before the call session starts. + + + Recordings may take a few minutes to process after the call ends. Check the Calls section in the [CometChat Dashboard](https://app.cometchat.com). If still missing, verify that recording was actually started (check `onRecordingStarted` callback). + + + +--- + +## Next Steps + + + + Start and manage call sessions with full configuration options + + + Implement a complete calling experience with incoming and outgoing call UI + + + Customize the main video container and participant tiles + + + Retrieve and display call history including duration and participants + + \ No newline at end of file diff --git a/sdk/react-native/resources-overview.mdx b/sdk/react-native/resources-overview.mdx index c9b7d6910..49e3abf37 100644 --- a/sdk/react-native/resources-overview.mdx +++ b/sdk/react-native/resources-overview.mdx @@ -1,12 +1,28 @@ --- title: "Resources" sidebarTitle: "Overview" +description: "Helpful resources for integrating CometChat into your React Native app, including real-time listeners, push notifications, and migration guides." --- - - We have a number of resources that will help you while integrating CometChat in your app. You can begin with the [all real-time listeners](/sdk/react-native/real-time-listeners) guide. If you're upgrading from v1, we recommend reading our [upgrading from v3](/sdk/react-native/upgrading-from-v3) guide. + +## Next Steps + + + +Register listeners for users, groups, messages, and calls + + +Set up FCM push notifications for Android + + +Set up APNs push notifications for iOS + + +Migration guide for upgrading from SDK v3 + + diff --git a/sdk/react-native/retrieve-conversations.mdx b/sdk/react-native/retrieve-conversations.mdx index 7b974c595..def5844c4 100644 --- a/sdk/react-native/retrieve-conversations.mdx +++ b/sdk/react-native/retrieve-conversations.mdx @@ -1,11 +1,38 @@ --- title: "Retrieve Conversations" +description: "Fetch recent one-on-one and group conversations for the logged-in user using the ConversationsRequestBuilder, with support for filtering, tagging, and pagination." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference for AI Agents & Developers** +```javascript +// Build a conversations request +let conversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(30) + .build(); + +// Fetch conversations (paginated) +conversationsRequest.fetchNext().then( + conversationList => console.log("Conversations:", conversationList), + error => console.log("Error:", error) +); + +// Retrieve a single conversation +CometChat.getConversation("UID_OR_GUID", "user_or_group").then( + conversation => console.log("Conversation:", conversation), + error => console.log("Error:", error) +); +``` + Conversations provide the last messages for every one-on-one and group conversation the logged-in user is a part of. This makes it easy for you to build a **Recent Chat** list. + +**Available via:** [SDK](/sdk/react-native/retrieve-conversations) | [REST API](/rest-api/conversations/list-conversations) | [UI Kits](/ui-kit/react-native/core-features#conversation-and-advanced-search) + + ## Retrieve List of Conversations *In other words, as a logged-in user, how do I retrieve the latest conversations that I've been a part of?* @@ -19,14 +46,13 @@ The `ConversationsRequestBuilder` class allows you to set the below parameters: This method sets the limit i.e. the number of conversations that should be fetched in a single iteration. - + ```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) .build(); ``` - @@ -36,9 +62,7 @@ let limit: number = 30, .setLimit(limit) .build(); ``` - - ### Set Conversation Type @@ -51,7 +75,7 @@ This method can be used to fetch user or group conversations specifically. The ` If none is set, the list of conversations will include both user and group conversations. - + ```javascript let limit = 30; let conversationType = "group"; @@ -60,7 +84,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setConversationType(conversationType) .build(); ``` - @@ -72,11 +95,135 @@ let limit: number = 30, .setConversationType(conversationType) .build(); ``` - - + +**On Success** — `fetchNext()` returns (only group conversations when `conversationType` is set to `"group"`): +```json +[ + { + "conversationId": "group_group_1748415903905", + "conversationType": "group", + "unreadMentionsCount": 0, + "lastReadMessageId": "25243", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1748415973, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 3, + "owner": "123456", + "scope": "admin", + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp", + "lastActiveAt": 1771413925, + "name": "Susan Marie", + "role": "admin", + "status": "online", + "tags": [], + "uid": "cometchat-uid-4" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_12-83d84373-9a70-4a11-a460-a71aecf16b3a-1771413918297", + "text": "Susan here " + }, + "text": "Susan here ", + "id": "25243", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-4", + "name": "Susan Marie", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp", + "lastActiveAt": 1771413925, + "role": "admin", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1748415973, + "onlineMembersCount": 3, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771413931, + "updatedAt": 1771413931, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25243", + "conversationWith": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "scope": "admin", + "joinedAt": 1748437105, + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "owner": "123456", + "updatedAt": 1771245340, + "onlineMembersCount": 1 + } + }, + // ... more conversations up to the specified limit +] +``` + + ### With User and Group Tags This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is false. @@ -90,7 +237,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .withUserAndGroupTags(true) .build(); ``` - @@ -101,11 +247,154 @@ let limit: number = 30, .withUserAndGroupTags(true) .build(); ``` - - + +`withUserAndGroupTags(true)` adds the `tags` array to the `conversationWith` object (user/group tags). The tags you see inside `lastMessage.data.entities` and `sender`/`receiver` are part of the message payload, not the conversation's `conversationWith` object. + + + +**On Success** — `fetchNext()` returns (conversations include user/group tags in `conversationWith`): +```json +[ + { + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25276", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771738926, + "role": "default", + "status": "offline" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771494233, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": ["userTag1"], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": ["userTag2"], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771738926 + } + } + }, + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "id": "25276", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "role": "default", + "status": "online", + "tags": ["userTag2"] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online", + "tags": ["userTag1"] + }, + "sentAt": 1771495242, + "deliveredAt": 1771495244, + "readAt": 1771495244, + "updatedAt": 1771495244, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25276", + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771818451, + "role": "default", + "status": "online", + "tags": ["userTag2"], + "conversationId": "cometchat-uid-2_user_cometchat-uid-3" + } + }, + // ... more conversations up to the specified limit +] +``` + + ### Set User Tags This method fetches user conversations that have the specified tags. @@ -120,7 +409,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setUserTags(userTags) .build(); ``` - @@ -132,11 +420,127 @@ let limit: number = 30, .setUserTags(userTags) .build(); ``` - - + +**On Success** — `fetchNext()` returns (only user conversations matching the specified user tags): +```json +[ + { + "conversationId": "cometchat-uid-2_user_cometchat-uid-5", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "24957", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-5", + "lastActiveAt": 1770973150, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": ["tag1"], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp", + "lastActiveAt": 1770973064, + "name": "John Paul", + "role": "admin", + "status": "online", + "tags": ["tag1"], + "uid": "cometchat-uid-5" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-7da177a5-3642-4571-acbb-d2f11b87f696-1770883672084", + "text": "Not yet, I will update you if any." + }, + "text": "Not yet, I will update you if any.", + "id": "24955", + "conversationId": "cometchat-uid-2_user_cometchat-uid-5", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-5", + "name": "John Paul", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp", + "lastActiveAt": 1770973064, + "role": "admin", + "status": "online", + "tags": ["tag1"] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1770973150, + "role": "default", + "status": "offline", + "tags": ["tag1"] + }, + "sentAt": 1770973162, + "editedAt": 1770973219, + "editedBy": "cometchat-uid-5", + "updatedAt": 1770973219, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "24957", + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-5", + "name": "John Paul", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp", + "lastActiveAt": 1771668031, + "role": "admin", + "status": "offline", + "conversationId": "cometchat-uid-2_user_cometchat-uid-5" + } + }, + // ... more conversations up to the specified limit +] +``` + + ### Set Group Tags This method fetches group conversations that have the specified tags. @@ -151,7 +555,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setGroupTags(groupTags) .build(); ``` - @@ -163,17 +566,144 @@ let limit: number = 30, .setGroupTags(groupTags) .build(); ``` - - + +**On Success** — `fetchNext()` returns (only group conversations matching the specified group tags): +```json +[ + { + "conversationId": "group_group_1748415903905", + "conversationType": "group", + "unreadMentionsCount": 0, + "lastReadMessageId": "25243", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1748415903905", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "guid": "group_1748415903905", + "hasJoined": true, + "joinedAt": 1748415973, + "membersCount": 12, + "name": "3 People Group", + "onlineMembersCount": 3, + "owner": "123456", + "scope": "admin", + "tags": ["tag1"], + "type": "public", + "updatedAt": 1771245340 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp", + "lastActiveAt": 1771413925, + "name": "Susan Marie", + "role": "admin", + "status": "online", + "tags": [], + "uid": "cometchat-uid-4" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_12-83d84373-9a70-4a11-a460-a71aecf16b3a-1771413918297", + "text": "Susan here " + }, + "text": "Susan here ", + "id": "25243", + "conversationId": "group_group_1748415903905", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-4", + "name": "Susan Marie", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp", + "lastActiveAt": 1771413925, + "role": "admin", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "tags": ["tag1"], + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "joinedAt": 1748415973, + "onlineMembersCount": 3, + "owner": "123456", + "scope": "admin", + "updatedAt": 1771245340 + }, + "sentAt": 1771413931, + "updatedAt": 1771413931, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25243", + "conversationWith": { + "hasJoined": true, + "membersCount": 12, + "isBanned": false, + "guid": "group_1748415903905", + "name": "3 People Group", + "type": "public", + "scope": "admin", + "joinedAt": 1748437105, + "conversationId": "group_group_1748415903905", + "createdAt": 1748415957, + "owner": "123456", + "updatedAt": 1771820149, + "updatedBy": "cometchat-uid-2", + "onlineMembersCount": 1 + } + }, + // ... more conversations up to the specified limit +] +``` + + ### With Tags -This method makes sure that the tags associated with the conversations are returned along with the other details of the conversations. The default value for this parameter is `false` +This method makes sure that the tags associated with the conversations are returned along with the other details of the conversations. The default value for this parameter is `false`. - + ```javascript let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() @@ -181,7 +711,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .withTags(true) .build(); ``` - @@ -192,17 +721,156 @@ let limit: number = 30, .withTags(true) .build(); ``` - - + +**On Success** — `fetchNext()` returns (conversations include `tags` field when `withTags` is set to `true`): +```json +[ + { + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25276", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771738926, + "role": "default", + "status": "offline" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771494233, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771738926 + } + } + }, + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "id": "25276", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771495242, + "deliveredAt": 1771495244, + "readAt": 1771495244, + "updatedAt": 1771495244, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25276", + "tags": ["archivedChat"], + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771818451, + "role": "default", + "status": "online", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3" + } + }, + // ... more conversations up to the specified limit +] +``` + + ### Set Tags This method helps you fetch the conversations based on the specified tags. - + ```javascript let limit = 30; let tags = ["archivedChat"]; @@ -211,7 +879,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setTags(tags) .build(); ``` - @@ -223,11 +890,163 @@ let limit: number = 30, .setTags(tags) .build(); ``` - - + +**On Success** — `fetchNext()` returns (only conversations matching the specified tags, e.g., `"archivedChat"`): +```json +[ + { + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25276", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771738926, + "role": "default", + "status": "offline" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771494233, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771738926 + } + } + }, + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "id": "25276", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771495242, + "deliveredAt": 1771495244, + "readAt": 1771495244, + "updatedAt": 1771495244, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25276", + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771818451, + "role": "default", + "status": "online", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3" + } + }, + // ... more conversations up to the specified limit +] +``` + + + +**Blocked Users in Conversations - Quick Reference** + +| Flag | Effect | +| ---- | ------ | +| `setIncludeBlockedUsers(true)` | Includes blocked user conversations in results (hidden by default) | +| `setWithBlockedInfo(true)` | Adds `blockedByMe`, `hasBlockedMe`, `blockedByMeAt`, `blockedAt` to `conversationWith` | + +**Usage:** +- Use both together to see blocked conversations with accurate block status +- `conversationWith` contains current block status +- `lastMessage.sender`/`receiver` contains historical data from message time (may show `false` even if currently blocked) + + ### Include Blocked Users This method helps you fetch the conversations of users whom the logged-in user has blocked. @@ -241,7 +1060,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setIncludeBlockedUsers(true) .build(); ``` - @@ -252,11 +1070,131 @@ let limit: number = 30, .setIncludeBlockedUsers(true) .build(); ``` - - + +**On Success** — `fetchNext()` returns (includes conversations with blocked users): +```json +[ + { + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25280", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "blockedAt": 1771820668, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "hasBlockedMe": true, + "hasBlockedMeAt": 1771820668, + "lastActiveAt": 1771738926, + "name": "George Alan", + "role": "default", + "status": "offline", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771818451, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Hello Blocker" + }, + "text": "Hello Blocker", + "id": "25280", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771818451, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771738926, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771820699, + "updatedAt": 1771820699, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25276", + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771738926, + "role": "default", + "status": "offline", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3" + } + }, + // ... more conversations up to the specified limit +] +``` + + ### With Blocked Info This method can be used to fetch the blocked information of the blocked user in the `ConversationWith` object. @@ -270,7 +1208,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setWithBlockedInfo(true) .build(); ``` - @@ -281,14 +1218,154 @@ let limit: number = 30, .setWithBlockedInfo(true) .build(); ``` - - + +**On Success** — `fetchNext()` returns (conversations include blocked info in `conversationWith`): +```json +[ + { + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25276", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [ + { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771738926, + "role": "default", + "status": "offline" + } + ], + "mentionedMe": true, + "receiverId": "cometchat-uid-2", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "lastActiveAt": 1771494233, + "name": "George Alan", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-2" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-0790756b-527d-443d-b3e6-6ce85a085e7f-1771494137056", + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "mentions": { + "cometchat-uid-2": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771738926 + } + } + }, + "text": "Message for mentioned users, Hello <@uid:cometchat-uid-2>", + "id": "25276", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771495034, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771494233, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771495242, + "deliveredAt": 1771495244, + "readAt": 1771495244, + "updatedAt": 1771495244, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25276", + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": true, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771818451, + "role": "default", + "status": "online", + "blockedByMeAt": 1771820668, + "blockedAt": 1771820668, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3" + } + }, + // ... more conversations up to the specified limit +] +``` + + ### Search Conversations -This method helps you search a conversation based on User or Group name. +This method helps you search for a conversation based on a User or Group name. @@ -305,7 +1382,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setSearchKeyword("Hiking") .build(); ``` - @@ -316,11 +1392,173 @@ let limit: number = 30, .setSearchKeyword("Hiking") .build(); ``` - - + +**On Success** — `fetchNext()` returns (conversations matching the search keyword `"Hiking"`): +```json +[ + { + "conversationId": "group_cometchat-guid-1", + "conversationType": "group", + "unreadMentionsCount": 0, + "lastReadMessageId": "4791", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-guid-1", + "type": "groupMember", + "receiverType": "group", + "category": "action", + "data": { + "action": "kicked", + "entities": { + "by": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp", + "createdAt": 1746375164, + "lastActiveAt": 1753945410, + "name": "John Paul", + "role": "default", + "status": "offline", + "uid": "cometchat-uid-5" + }, + "entityType": "user" + }, + "for": { + "entity": { + "conversationId": "group_cometchat-guid-1", + "createdAt": 1746375164, + "description": "Explore, connect, and chat with fellow outdoor enthusiasts, thanks to our CometChat-enabled community platform.", + "guid": "cometchat-guid-1", + "icon": "https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp", + "membersCount": 3, + "name": "Hiking Group", + "owner": "cometchat-uid-5", + "type": "private", + "updatedAt": 1753945144 + }, + "entityType": "group" + }, + "on": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp", + "conversationId": "cometchat-uid-1_user_cometchat-uid-5", + "createdAt": 1746375164, + "lastActiveAt": 1753944766, + "name": "Andrew Joseph", + "role": "default", + "status": "offline", + "statusMessage": "Hey there I'm using CometChat", + "uid": "cometchat-uid-1", + "updatedAt": 1749731589 + }, + "entityType": "user" + } + } + }, + "action": "kicked", + "actionBy": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-5", + "name": "John Paul", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp", + "lastActiveAt": 1753945410, + "role": "default", + "status": "offline", + "createdAt": 1746375164 + }, + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-5", + "name": "John Paul", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp", + "lastActiveAt": 1753945410, + "role": "default", + "status": "offline", + "createdAt": 1746375164 + }, + "actionFor": { + "hasJoined": false, + "membersCount": 3, + "isBanned": false, + "guid": "cometchat-guid-1", + "conversationId": "group_cometchat-guid-1", + "createdAt": 1746375164, + "description": "Explore, connect, and chat with fellow outdoor enthusiasts, thanks to our CometChat-enabled community platform.", + "icon": "https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp", + "name": "Hiking Group", + "owner": "cometchat-uid-5", + "type": "private", + "updatedAt": 1753945144 + }, + "actionOn": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-1", + "name": "Andrew Joseph", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp", + "lastActiveAt": 1753944766, + "role": "default", + "statusMessage": "Hey there I'm using CometChat", + "status": "offline", + "conversationId": "cometchat-uid-1_user_cometchat-uid-5", + "createdAt": 1746375164, + "updatedAt": 1749731589 + }, + "message": "John Paul kicked Andrew Joseph", + "id": "4791", + "conversationId": "group_cometchat-guid-1", + "receiver": { + "hasJoined": false, + "membersCount": 3, + "isBanned": false, + "guid": "cometchat-guid-1", + "conversationId": "group_cometchat-guid-1", + "createdAt": 1746375164, + "description": "Explore, connect, and chat with fellow outdoor enthusiasts, thanks to our CometChat-enabled community platform.", + "icon": "https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp", + "name": "Hiking Group", + "owner": "cometchat-uid-5", + "type": "private", + "updatedAt": 1753945144 + }, + "sentAt": 1753946954, + "deliveredAt": 1764150385, + "updatedAt": 1764150385 + }, + "latestMessageId": "4791", + "conversationWith": { + "hasJoined": true, + "membersCount": 3, + "isBanned": false, + "guid": "cometchat-guid-1", + "name": "Hiking Group", + "type": "private", + "description": "Explore, connect, and chat with fellow outdoor enthusiasts, thanks to our CometChat-enabled community platform.", + "icon": "https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp", + "scope": "participant", + "joinedAt": 1746375164, + "conversationId": "group_cometchat-guid-1", + "createdAt": 1746375164, + "owner": "cometchat-uid-5", + "updatedAt": 1753946955, + "onlineMembersCount": 1 + } + }, + // ... more conversations up to the specified limit +] +``` + + ### Unread Conversations This method helps you fetch unread conversations. @@ -340,7 +1578,6 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() .setUnread(true) .build(); ``` - @@ -351,11 +1588,135 @@ let limit: number = 30, .setUnread(true) .build(); ``` - - + +**On Success** — `fetchNext()` returns (only unread conversations): +```json +[ + { + "conversationId": "group_group_1762515421478", + "conversationType": "group", + "unreadMentionsCount": 0, + "lastReadMessageId": "24359", + "unreadMessageCount": 2, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "group_1762515421478", + "type": "text", + "receiverType": "group", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "conversationId": "group_group_1762515421478", + "createdAt": 1762515421, + "guid": "group_1762515421478", + "hasJoined": true, + "joinedAt": 1762515534, + "membersCount": 3, + "name": "TwoMemberGroup", + "onlineMembersCount": 2, + "owner": "cometchat-uid-2", + "scope": "participant", + "type": "public", + "updatedAt": 1768888876 + }, + "entityType": "group" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "name": "Nancy Grace", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-3" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-de89d7ce-f090-4e2e-ad89-bebae957b3ff-1771397690356", + "text": "Hru" + }, + "text": "Hru", + "id": "25236", + "conversationId": "group_group_1762515421478", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771397739, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasJoined": true, + "membersCount": 3, + "isBanned": false, + "guid": "group_1762515421478", + "name": "TwoMemberGroup", + "type": "public", + "conversationId": "group_group_1762515421478", + "createdAt": 1762515421, + "joinedAt": 1762515534, + "onlineMembersCount": 2, + "owner": "cometchat-uid-2", + "scope": "participant", + "updatedAt": 1768888876 + }, + "sentAt": 1771400675, + "updatedAt": 1771400675, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25236", + "conversationWith": { + "hasJoined": true, + "membersCount": 3, + "isBanned": false, + "guid": "group_1762515421478", + "name": "TwoMemberGroup", + "type": "public", + "scope": "admin", + "joinedAt": 1762515421, + "conversationId": "group_group_1762515421478", + "createdAt": 1762515421, + "owner": "cometchat-uid-2", + "updatedAt": 1768888876, + "onlineMembersCount": 1 + } + }, + // ... more conversations up to the specified limit +] +``` + + Finally, once all the parameters are set to the builder class, you need to call the `build()` method to get the object of the `ConversationsRequest` class. Once you have the object of the `ConversationsRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `Conversation` objects containing X number of users depending on the limit set. @@ -363,7 +1724,7 @@ Once you have the object of the `ConversationsRequest` class, you need to call t A Maximum of only 50 Conversations can be fetched at once. - + ```javascript let limit = 30; let conversationsRequest = new CometChat.ConversationsRequestBuilder() @@ -378,7 +1739,6 @@ conversationsRequest.fetchNext().then( } ); ``` - @@ -396,9 +1756,7 @@ conversationsRequest.fetchNext().then( } ); ``` - - The `Conversation` Object consists of the following fields: @@ -407,7 +1765,7 @@ The `Conversation` Object consists of the following fields: | ------------------ | ----------------------------------------------------------------- | | conversationId | ID of the conversation. | | conversationType | Type of conversation. (user/group) | -| lastMessage | Last message the conversation. | +| lastMessage | Last message in the conversation. | | conversationWith | User or Group object containing the details of the user or group. | | unreadMessageCount | Unread message count for the conversation. | @@ -417,7 +1775,7 @@ The `Conversation` Object consists of the following fields: To tag a specific conversation, you can use the `tagConversation()` method. The `tagConversation()` method accepts three parameters. -1. `conversationWith`: UID/GUID of the user/group whose conversation you want to fetch. +1. `conversationWith`: UID/GUID of the user/group whose conversation you want to tag. 2. `conversationType`: The `conversationType` variable can hold one of the below two values: @@ -427,7 +1785,7 @@ To tag a specific conversation, you can use the `tagConversation()` method. The 3. `tags`: The `tags` variable will be a list of tags you want to add to a conversation. - + ```javascript let tags = ["archivedChat"]; CometChat.tagConversation('conversationWith', 'conversationType', tags).then( @@ -438,11 +1796,125 @@ CometChat.tagConversation('conversationWith', 'conversationType', tags).then( } ); ``` - - + +**On Success** — `tagConversation()` returns the updated conversation object with the new tags: +```json +{ + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25291", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-6", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771829859, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-b495efdd-5a54-4a47-a8ad-237bf8dff679-1771829544163", + "text": "Hello" + }, + "text": "Hello", + "id": "25291", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771829859, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771831336, + "deliveredAt": 1771832977, + "readAt": 1771832977, + "updatedAt": 1771832977, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25291", + "tags": ["archivedChat"], + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771834604, + "role": "default", + "status": "online", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7" + } +} +``` + + The tags for conversations are one-way. This means that if user A tags a conversation with user B, that tag will be applied to that conversation only for user A. @@ -462,7 +1934,7 @@ To fetch a specific conversation, you can use the `getConversation` method. The * group - Only fetches group conversations. - + ```javascript CometChat.getConversation('conversationWith', 'conversationType').then( conversation => { @@ -472,17 +1944,132 @@ CometChat.getConversation('conversationWith', 'conversationType').then( } ); ``` - - + +**On Success** — `getConversation()` returns the conversation object: +```json +{ + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "25291", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-6", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771829859, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-b495efdd-5a54-4a47-a8ad-237bf8dff679-1771829544163", + "text": "Hello" + }, + "text": "Hello", + "id": "25291", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771829859, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771831336, + "deliveredAt": 1771832977, + "readAt": 1771832977, + "updatedAt": 1771832977, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "25291", + "tags": ["archivedChat"], + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771834604, + "role": "default", + "status": "online", + "tags": [], + "conversationId": "cometchat-uid-6_user_cometchat-uid-7" + } +} +``` + + ## Convert Messages to Conversations -As per our [receive messages](/sdk/react-native/receive-messages) guide, for real-time messages, you will always receive `Message` objects and not `Conversation` objects. Thus, you will need a mechanism to convert the Message object to `Conversation` object. You can use the `getConversationFromMessage(BaseMessage message)` of the `CometChatHelper` class. +As per our [receive messages](/sdk/react-native/receive-messages) guide, for real-time messages, you will always receive `Message` objects and not `Conversation` objects. Thus, you will need a mechanism to convert the Message object to a `Conversation` object. You can use the `getConversationFromMessage(BaseMessage message)` method of the `CometChatHelper` class. - + ```javascript CometChat.CometChatHelper.getConversationFromMessage(message).then( conversation => { @@ -492,13 +2079,258 @@ conversation => { } ); ``` - - + +**Source Message Object:** +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-6", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771829859, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-b495efdd-5a54-4a47-a8ad-237bf8dff679-1771829544163", + "text": "Hello" + }, + "text": "Hello", + "id": "25291", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771829859, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771831336, + "deliveredAt": 1771832977, + "readAt": 1771832977, + "updatedAt": 1771832977, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} +``` + +**On Success** — `getConversationFromMessage()` returns the converted conversation object: +```json +{ + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "conversationType": "user", + "unreadMentionsCount": 0, + "lastReadMessageId": "", + "unreadMessageCount": 0, + "lastMessage": { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-6", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771829859, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-b495efdd-5a54-4a47-a8ad-237bf8dff679-1771829544163", + "text": "Hello" + }, + "text": "Hello", + "id": "25291", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771829859, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771831336, + "deliveredAt": 1771832977, + "readAt": 1771832977, + "updatedAt": 1771832977, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + "latestMessageId": "", + "conversationWith": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "role": "default", + "status": "online", + "tags": [] + } +} +``` + + While converting the `Message` object to the `Conversation` object, the `unreadMessageCount` & `tags` will not be available in the `Conversation` object. The unread message count needs to be managed in your client-side code. + +## Best Practices & Troubleshooting + + + + Always use `fetchNext()` in a loop or on-scroll handler to paginate through conversations. Fetching all conversations at once is not supported — the maximum per request is 50. Store the `ConversationsRequest` object and call `fetchNext()` repeatedly until it returns an empty list. + + + Use [real-time message listeners](/sdk/react-native/receive-messages) to receive new messages, then call `CometChatHelper.getConversationFromMessage()` to convert incoming messages into `Conversation` objects and update your list. Note that `unreadMessageCount` and `tags` are not available when converting from a message — manage those on the client side. + + + Use `setTags()` to categorize conversations (e.g., `archivedChat`, `pinned`). Remember that conversation tags are one-way — tagging a conversation only applies for the logged-in user, not the other participant. + + + Ensure the logged-in user has actually exchanged messages with the expected users or groups. Conversations only appear once at least one message has been sent. Also verify that any filters (conversation type, tags, unread) are not excluding the results you expect. + + + The `setSearchKeyword()` and `setUnread()` methods require the `Conversation & Advanced Search` feature, which is only available on `Advanced` and `Custom` [plans](https://www.cometchat.com/pricing). Enable it from the [CometChat Dashboard](https://app.cometchat.com) under Chats → Settings → General Configuration. + + + +--- + +## Next Steps + + + + Remove a conversation from the logged-in user's conversation list. + + + Listen for real-time messages and update your conversation list. + + + Show real-time typing status within conversations. + + + Track when messages are delivered and read. + + diff --git a/sdk/react-native/retrieve-group-members.mdx b/sdk/react-native/retrieve-group-members.mdx index 2c81e28d2..ec1b16002 100644 --- a/sdk/react-native/retrieve-group-members.mdx +++ b/sdk/react-native/retrieve-group-members.mdx @@ -1,8 +1,22 @@ --- title: "Retrieve Group Members" +description: "Fetch group member lists with filtering by scope, search, and pagination using the CometChat React Native SDK." --- + +**Quick Reference** - Fetch group members: +```javascript +const request = new CometChat.GroupMembersRequestBuilder("GUID") + .setLimit(30) + .build(); +const members = await request.fetchNext(); +``` + + + +**Available via:** [SDK](/sdk/react-native/retrieve-group-members) | [REST API](/rest-api/group-members/list) | [UI Kits](/ui-kit/react-native/groups) + ## Retrieve the List of Group Members @@ -17,7 +31,7 @@ The GUID of the group for which the members are to be fetched must be specified This method sets the limit i.e. the number of members that should be fetched in a single iteration. - + ```javascript let GUID = "GUID"; let limit = 30; @@ -46,7 +60,7 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb This method allows you to set the search string based on which the group members are to be fetched. - + ```javascript let GUID = "GUID"; let limit = 30; @@ -79,7 +93,7 @@ let groupMembersRequest: CometChat.GroupMembersRequest = new CometChat.GroupMemb This method allows you to fetch group members based on multiple scopes. - + ```javascript let GUID = "GUID"; let limit = 30; @@ -112,7 +126,7 @@ Finally, once all the parameters are set to the builder class, you need to call Once you have the object of the `GroupMembersRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `GroupMember` objects containing n number of members where n is the limit set in the builder class. - + ```javascript let GUID = "GUID"; let limit = 30; @@ -151,3 +165,47 @@ groupMembersRequest.fetchNext().then( + +## Best Practices + + + + Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30). For groups with many members, paginate through results rather than fetching all at once. + + + The `GroupMembersRequest` object maintains an internal cursor. Creating a new instance resets the cursor. Reuse the same instance across `fetchNext()` calls. + + + Use `setScopes()` to fetch only admins or moderators when building admin management UIs, rather than fetching all members and filtering client-side. + + + +## Troubleshooting + + + + Verify the GUID is correct and the logged-in user is a member of the group. Non-members cannot fetch the member list of private groups. + + + Ensure you're reusing the same `GroupMembersRequest` instance. Creating a new builder resets the pagination cursor. + + + +--- + +## Next Steps + + + + Add new members to a group + + + Kick, ban, and unban group members + + + Update member roles within a group + + + Fetch group lists and group details + + \ No newline at end of file diff --git a/sdk/react-native/retrieve-groups.mdx b/sdk/react-native/retrieve-groups.mdx index f8d42c0ab..016e07c3e 100644 --- a/sdk/react-native/retrieve-groups.mdx +++ b/sdk/react-native/retrieve-groups.mdx @@ -1,8 +1,27 @@ --- title: "Retrieve Groups" +description: "Fetch group lists, search groups, get group details, and retrieve online member counts using the CometChat React Native SDK." --- + +**Quick Reference** - Fetch groups: +```javascript +// Fetch group list +const groupsRequest = new CometChat.GroupsRequestBuilder().setLimit(30).build(); +const groups = await groupsRequest.fetchNext(); + +// Get specific group +const group = await CometChat.getGroup("GUID"); + +// Get online member count +const counts = await CometChat.getOnlineGroupMemberCount(["GUID"]); +``` + + + +**Available via:** [SDK](/sdk/react-native/retrieve-groups) | [REST API](/rest-api/groups/list) | [UI Kits](/ui-kit/react-native/groups) + ## Overview @@ -19,7 +38,7 @@ The `GroupsRequestBuilder` class allows you to set the below parameters: This method sets the limit i.e. the number of groups that should be fetched in a single iteration. - + ```javascript let limit = 30; let groupsRequest = new CometChat.GroupsRequestBuilder() @@ -45,7 +64,7 @@ let groupsRequest: CometChat.GroupsRequest = This method allows you to set the search string based on which the groups are to be fetched. - + ```javascript let limit = 30; let searchKeyword = "group"; @@ -77,7 +96,7 @@ let groupsRequest: CometChat.GroupsRequest = This method when used, will ask the SDK to only return the groups that the user has joined or is a part of. - + ```javascript let limit = 30; let groupsRequest = new CometChat.GroupsRequestBuilder() @@ -104,7 +123,7 @@ let groupsRequest: CometChat.GroupsRequest = This method accepts a list of tags based on which the list of groups is to be fetched. The list fetched will only contain the groups that have been tagged with the specified tags. - + ```javascript let limit = 30; let tags = ["tag1", "tag2"]; @@ -133,7 +152,7 @@ let groupsRequest: CometChat.GroupsRequest = This property when set to true will fetch tags data along with the list of groups. - + ```javascript let limit = 30; let groupsRequest = new CometChat.GroupsRequestBuilder() @@ -162,7 +181,7 @@ Once you have the object of the `GroupsRequest` class, you need to call the `fet The list of groups fetched will only have the public and password type groups. The private groups will only be available if the user is a member of the group. - + ```javascript let limit = 30; let groupsRequest = new CometChat.GroupsRequestBuilder() @@ -208,7 +227,7 @@ groupsRequest.fetchNext().then( To get the information of a group, you can use the `getGroup()` method. - + ```javascript var GUID = "GUID"; CometChat.getGroup(GUID).then( @@ -251,7 +270,7 @@ It returns `Group` object containing the details of the group. To get the total count of online users in particular groups, you can use the `getOnlineGroupMemberCount()` method. - + ```javascript let guids = ["cometchat-guid-1"]; CometChat.getOnlineGroupMemberCount(guids).then( @@ -284,3 +303,50 @@ CometChat.getOnlineGroupMemberCount(guids).then( This method returns a JSON Object with the GUID as the key and the online member count for that group as the value. + +## Best Practices + + + + Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30) rather than fetching all groups at once. This improves performance and reduces memory usage. + + + The `GroupsRequest` object maintains an internal cursor. Creating a new instance resets the cursor, causing the same page to be fetched repeatedly. Reuse the same instance across `fetchNext()` calls. + + + When displaying "My Groups" in your UI, use `joinedOnly(true)` to fetch only groups the user belongs to, rather than filtering the full list client-side. + + + +## Troubleshooting + + + + Private groups are only returned if the logged-in user is a member. This is by design — use `joinedOnly(true)` to see all groups the user has access to, including private ones. + + + Verify the logged-in user session is active. Also check if filters like `setTags` or `setSearchKeyword` are too restrictive. Try removing filters to confirm groups exist. + + + Ensure the GUID exists in your CometChat app. GUIDs are case-sensitive — double-check the exact GUID string. + + + +--- + +## Next Steps + + + + Create public, private, or password-protected groups + + + Join public or password-protected groups + + + Manage members, roles, and permissions within groups + + + Send text, media, and custom messages to groups + + \ No newline at end of file diff --git a/sdk/react-native/retrieve-users.mdx b/sdk/react-native/retrieve-users.mdx index 6e190313a..73a1601ff 100644 --- a/sdk/react-native/retrieve-users.mdx +++ b/sdk/react-native/retrieve-users.mdx @@ -1,15 +1,34 @@ --- title: "Retrieve Users" +description: "Fetch user lists, search users, get logged-in user details, and retrieve online user counts using the CometChat React Native SDK." --- + +**Quick Reference** - Fetch users: +```javascript +// Get logged-in user +const me = await CometChat.getLoggedinUser(); + +// Fetch user list +const usersRequest = new CometChat.UsersRequestBuilder().setLimit(30).build(); +const users = await usersRequest.fetchNext(); + +// Get specific user +const user = await CometChat.getUser("UID"); +``` + + + +**Available via:** [SDK](/sdk/react-native/retrieve-users) | [REST API](/rest-api/users/list) | [UI Kits](/ui-kit/react-native/users) + ## Retrieve Logged In User Details You can get the details of the logged-in user using the `getLoggedInUser()` method. This method can also be used to check if the user is logged in or not. If the method returns `Promise` with reject callback, it indicates that the user is not logged in and you need to log the user into CometChat SDK. - + ```javascript var user = CometChat.getLoggedinUser().then( user => { @@ -37,6 +56,29 @@ CometChat.getLoggedinUser().then( + +**On Success** — `getLoggedinUser()` returns a `User` object containing the logged-in user's details: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | +| `authToken` | string | Authentication token for the user | `"cometchat-uid-7_177199269018c2c2995f0b69b3844abc9fdb9843"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771853565` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `tags` | array | Tags associated with the user | `["vip"]` | + + + This method will return a `User` object containing all the information related to the logged-in user. ## Retrieve List of Users @@ -50,7 +92,7 @@ The `UsersRequestBuilder` class allows you to set the below parameters: This method sets the limit i.e. the number of users that should be fetched in a single iteration. - + ```javascript let limit = 30; let usersRequest = new CometChat.UsersRequestBuilder() @@ -72,12 +114,30 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with basic limit returns an array of `User` objects: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | + + + ### Set Search Keyword This method allows you to set the search string based on which the users are to be fetched. - + ```javascript let limit = 30; let searchKeyword = "super"; @@ -138,6 +198,27 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with search filter returns an array of `User` objects matching the search criteria: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"123456"` | +| `name` | string | Display name of the user | `"Farhan Ahmed"` | +| `avatar` | string | URL to user's avatar image | `"https://st2.depositphotos.com/38197074/46684/v/450/depositphotos_466848082-stock-illustration-initial-letter-vector-logo.jpg"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"extrarole"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1768988601` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `true` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `metadata` | object | Custom metadata attached to the user | `{"metadata": "something"}` | +| `blockedByMeAt` | number | Timestamp when blocked by current user | `1772164515` | +| `blockedAt` | number | Timestamp of block action | `1772164515` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"123456_user_cometchat-uid-7"` | + + + ### Set Status The status based on which the users are to be fetched. The status parameter can contain one of the below two values: @@ -148,7 +229,7 @@ The status based on which the users are to be fetched. The status parameter can If this parameter is not set, will return all the available users. - + ```javascript let limit = 30; let usersRequest = new CometChat.UsersRequestBuilder() @@ -172,12 +253,30 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with status filter returns an array of `User` objects with matching status: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | + + + ### Hide Blocked Users This method is used to determine if the blocked users should be returned as a part of the user list. If set to true, the user list will not contain the users blocked by the logged in user. - + ```javascript let limit = 30; let usersRequest = new CometChat.UsersRequestBuilder() @@ -201,12 +300,30 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with `hideBlockedUsers(true)` returns an array of `User` objects excluding blocked users: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | + + + ### Set Roles This method allows you to fetch the users based on multiple roles. - + ```javascript let limit = 30; let roles = ["default", "dev"]; @@ -232,12 +349,30 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with roles filter returns an array of `User` objects with matching roles: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | + + + ### Friends Only This property when set to true will return only the friends of the logged-in user. - + ```javascript let limit = 30; let usersRequest = new CometChat.UsersRequestBuilder() @@ -261,12 +396,30 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with `friendsOnly(true)` returns an array of `User` objects who are friends: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | + + + ### Set Tags This method accepts a list of tags based on which the list of users is to be fetched. The list fetched will only contain the users that have been tagged with the specified tags. - + ```javascript let limit = 30; let tags = ["tag1", "tag2"]; @@ -292,12 +445,29 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with tags filter returns an array of `User` objects with matching tags: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"user509"` | +| `name` | string | Display name of the user | `"again stokes"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1759921301` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-7_user_user509"` | + + + ### With Tags This property when set to true will fetch tags data along with the list of users. - + ```javascript let limit = 30; let usersRequest = new CometChat.UsersRequestBuilder() @@ -321,12 +491,31 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with `withTags(true)` returns an array of `User` objects including the `tags` field: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `tags` | array | Tags associated with the user | `["vip"]` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | + + + ### Set UIDs This method accepts a list of UIDs based on which the list of users is fetched. A maximum of `25` users can be fetched. - + ```javascript let limit = 30; let UIDs = ["cometchat-uid-1", "cometchat-uid-2"]; @@ -352,6 +541,24 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with UIDs filter returns an array of `User` objects for the specified UIDs: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-5"` | +| `name` | string | Display name of the user | `"John Paul"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"admin"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772087140` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-5_user_cometchat-uid-7"` | + + + ### Sort By This method allows you to sort the User List by a specific property of User. By default the User List is sorted by `status => name => UID` . If `name` is pass to the `sortBy()` method the user list will be sorted by `name => UID`. @@ -384,6 +591,23 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with `sortBy("name")` returns an array of `User` objects sorted by name: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"1"` | +| `name` | string | Display name of the user | `"1"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1770017972` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"1_user_cometchat-uid-7"` | + + + ### Sort By Order This method allows you to sort the User List in a specific order. By default the user list is sorted in ascending order. @@ -415,12 +639,29 @@ let usersRequest: CometChat.UsersRequest = new CometChat.UsersRequestBuilder() + +**On Success** — `fetchNext()` with `sortByOrder("desc")` returns an array of `User` objects in descending order: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"voip3"` | +| `name` | string | Display name of the user | `"voip3"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1770193733` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-7_user_voip3"` | + + + Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the UsersRequest class. Once you have the object of the UsersRequest class, you need to call the fetchNext() method. Calling this method will return a list of User objects containing n number of users where n is the limit set in the builder class. - + ```javascript var limit = 30; var usersRequest = new CometChat.UsersRequestBuilder() @@ -458,12 +699,38 @@ usersRequest.fetchNext().then( + +**On Success** — `fetchNext()` returns an array of `User` objects: + + + +**User Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://media.istockphoto.com/id/1682296067/photo/happy-studio-portrait-or-professional-man-real-estate-agent-or-asian-businessman-smile-for.jpg?s=612x612&w=0&k=20&c=9zbG2-9fl741fbTWw5fNgcEEe4ll-JegrGlQQ6m54rg="` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163872` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | Tags associated with the user (when `withTags(true)`) | `["vip"]` | +| `metadata` | object | Custom metadata attached to the user (if set) | `{"metadata": "something"}` | +| `blockedByMeAt` | number | Timestamp when blocked by current user (if blocked) | `1772164515` | +| `blockedAt` | number | Timestamp of block action (if blocked) | `1772164515` | + + + ## Retrieve Particular User Details To get the information of a user, you can use the `getUser()` method. - + ```javascript let UID = "UID"; CometChat.getUser(UID).then( @@ -499,14 +766,35 @@ The `getUser()` method takes the following parameters: | --------- | ---------------------------------------------------------- | | UID | The UID of the user for whom the details are to be fetched | -It returns the `User` object containing the details of the user. + +**On Success** — `getUser()` returns a `User` object containing the requested user's details: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-5"` | +| `name` | string | Display name of the user | `"John Paul"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"admin"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772087140` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `tags` | array | Tags associated with the user | `["tag1"]` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-5_user_cometchat-uid-7"` | + + ## Get online user count To get the total count of online users for your app, you can use the `getOnlineUserCount()` method. - + ```javascript CometChat.getOnlineUserCount().then( userCount => { @@ -534,4 +822,64 @@ CometChat.getOnlineUserCount().then( + +**On Success** — `getOnlineUserCount()` returns an object with the count: + + + +**Response Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `count` | number | Total number of online users | `2` | + + + This method returns the total online user count for your app. + +## Best Practices + + + + Always use `fetchNext()` with a reasonable `setLimit()` value (e.g., 20-30) rather than fetching all users at once. This improves performance and reduces memory usage. + + + The `UsersRequest` object maintains an internal cursor. Creating a new instance resets the cursor, causing the same page to be fetched repeatedly. Reuse the same instance across `fetchNext()` calls. + + + Use the builder's filter methods (`setSearchKeyword`, `setStatus`, `setRoles`, `setTags`) to narrow results at the API level rather than fetching all users and filtering in your app. + + + +## Troubleshooting + + + + Verify the logged-in user session is active. Also check if filters like `setRoles`, `setTags`, or `setStatus` are too restrictive. Try removing filters to confirm users exist. + + + Ensure the UID exists in your CometChat app. UIDs are case-sensitive — double-check the exact UID string. + + + By default, blocked users are included in the user list. Use `hideBlockedUsers(true)` in the `UsersRequestBuilder` to exclude them. + + + +--- + +## Next Steps + + + + Create, update, and delete users in CometChat + + + Block and unblock users, retrieve blocked user lists + + + Track online/offline status of users in real time + + + Fetch conversation lists with last message and unread counts + + \ No newline at end of file diff --git a/sdk/react-native/send-message.mdx b/sdk/react-native/send-message.mdx index 9a7da6b27..76e1dd137 100644 --- a/sdk/react-native/send-message.mdx +++ b/sdk/react-native/send-message.mdx @@ -1,15 +1,34 @@ --- title: "Send A Message" +description: "Send text, media, and custom messages to users and groups using the CometChat React Native SDK." --- + +**Quick Reference** - Send a text message: +```javascript +// Send text to a user +const textMessage = new CometChat.TextMessage("UID", "Hello!", CometChat.RECEIVER_TYPE.USER); +const sent = await CometChat.sendMessage(textMessage); + +// Send media to a group +const mediaMessage = new CometChat.MediaMessage("GUID", file, CometChat.MESSAGE_TYPE.IMAGE, CometChat.RECEIVER_TYPE.GROUP); +const sentMedia = await CometChat.sendMediaMessage(mediaMessage); +``` + + + +**Available via:** [SDK](/sdk/react-native/send-message) | [REST API](/rest-api/messages/send-message) | [UI Kits](/ui-kit/react-native/core-features#instant-messaging) + Using CometChat, you can send three types of messages: -1. [Text Message](/sdk/react-native/send-message#text-message) is the most common and standard message type. -2. [Media Message](/sdk/react-native/send-message#media-message), for sending photos, videos and files. -3. [custom message](/sdk/react-native/send-message#custom-message), for sending completely custom data using JSON structures. -4. [Interactive Message](/sdk/react-native/interactive-messages) for sending end-user interactive messages of type form, card and custom Interactive You can also send metadata along with a text, media or custom message. Think, for example, if you want to share the user's location with every message, you can use the metadata field. +1. [Text Message](#text-message) is the most common and standard message type. +2. [Media Message](#media-message), for sending photos, videos and files. +3. [Custom Message](#custom-message), for sending completely custom data using JSON structures. +4. [Interactive Message](/sdk/react-native/interactive-messages) for sending end-user interactive messages of type form, card and custom interactive. + +You can also send metadata along with a text, media or custom message. Think, for example, if you want to share the user's location with every message, you can use the metadata field. ## Text Message @@ -22,30 +41,26 @@ To send a text message to a single user or group, you need to use the `sendMessa To send custom data along with a text message, you can use the `setMetadata` method and pass a `JSON Object` to it. - -```javascript -let metadata = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -textMessage.setMetadata(metadata); -``` - - - - -```typescript -let metadata: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -textMessage.setMetadata(metadata); -``` - - - + + ```javascript + let metadata = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + + textMessage.setMetadata(metadata); + ``` + + + ```typescript + let metadata: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + + textMessage.setMetadata(metadata); + ``` + ### Add Tags @@ -53,121 +68,109 @@ textMessage.setMetadata(metadata); To add a tag to a message you can use the `setTags()` method of the TextMessage Class. The `setTags()` method accepts a list of tags. - -```javascript -let tags = ["starredMessage"]; - -textMessage.setTags(tags); -``` - - - - -```typescript -let tags: Array = ["starredMessage"]; - -textMessage.setTags(tags); -``` - - - + + ```javascript + let tags = ["starredMessage"]; + + textMessage.setTags(tags); + ``` + + + ```typescript + let tags: Array = ["starredMessage"]; + + textMessage.setTags(tags); + ``` + Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. - -```javascript -let receiverID = "UID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` + + ```javascript + let receiverID = "UID"; + let messageText = "Hello world!"; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + + CometChat.sendMessage(textMessage).then( + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + + + ```javascript + let receiverID = "GUID"; + let messageText = "Hello world!"; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + + CometChat.sendMessage(textMessage).then( + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "UID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); - + CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "GUID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + The `TextMessage` class constructor takes the following parameters: @@ -180,127 +183,221 @@ The `TextMessage` class constructor takes the following parameters: When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. -### Set Quoted Message Id - -To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the TextMessage class. This method accepts the ID of the message to be quoted. - - - -```javascript -textMessage.setQuotedMessageId(10); + +**On Success** — `console.log("Message sent successfully:", message)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "text": "Hello world!", + "resource": "REACT_NATIVE-4_0_13-398e7dd2-3481-44ed-8837-eadf1c9c6f5d-1771320626645", + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771320632, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771320647, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "tags": [] + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "pending" + } + }, + "text": "Hello world!", + "id": "25182", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771320632, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771320647, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771320772, + "updatedAt": 1771320772, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} ``` - - - -```typescript -textMessage.setQuotedMessageId(10); +**On Failure** — `console.log("Message sending failed with error:", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in. Please log in before sending a message.", + "details": {} +} ``` + - +### Set Quoted Message Id +To set a quoted message ID for a message, use the `setQuotedMessageId()` method of the TextMessage class. This method accepts the ID of the message to be quoted. + + + + ```javascript + textMessage.setQuotedMessageId(10); + ``` + + + ```typescript + textMessage.setQuotedMessageId(10); + ``` + Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. - -```javascript -let receiverID = "UID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageText = "Hello world!"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let textMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType -); - -CometChat.sendMessage(textMessage).then( - (message) => { - console.log("Message sent successfully:", message); - }, - (error) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageText: string = "Hello world!", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - textMessage: CometChat.TextMessage = new CometChat.TextMessage( - receiverID, - messageText, - receiverType - ); - -CometChat.sendMessage(textMessage).then( - (message: CometChat.TextMessage) => { - console.log("Message sent successfully:", message); - }, - (error: CometChat.CometChatException) => { - console.log("Message sending failed with error:", error); - } -); -``` + + ```javascript + let receiverID = "UID"; + let messageText = "Hello world!"; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + + CometChat.sendMessage(textMessage).then( + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + + + ```javascript + let receiverID = "GUID"; + let messageText = "Hello world!"; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let textMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + + CometChat.sendMessage(textMessage).then( + (message) => { + console.log("Message sent successfully:", message); + }, + (error) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "UID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); - + CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "GUID", + messageText: string = "Hello world!", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + textMessage: CometChat.TextMessage = new CometChat.TextMessage( + receiverID, + messageText, + receiverType + ); + CometChat.sendMessage(textMessage).then( + (message: CometChat.TextMessage) => { + console.log("Message sent successfully:", message); + }, + (error: CometChat.CometChatException) => { + console.log("Message sending failed with error:", error); + } + ); + ``` + The `TextMessage` class constructor takes the following parameters: -| Parameter | Description | | +| Parameter | Description | Required | | ---------------- | -------------------------------------------------------------------------------------------- | -------- | | **receiverID** | `UID` of the user or `GUID` of the group receiving the message | Required | | **messageText** | The text message | Required | @@ -308,7 +405,6 @@ The `TextMessage` class constructor takes the following parameters: When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. - ## Media Message *In other words, as a sender, how do I send a media message like photos, videos & files?* @@ -320,55 +416,47 @@ To send a media message to any user or group, you need to use the `sendMediaMess To send custom data along with a media message, you can use the `setMetadata` method and pass a `JSON Object` to it. - -```javascript -let metadata = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -mediaMessage.setMetadata(metadata); -``` - - - - -```typescript -let metadata: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; - -mediaMessage.setMetadata(metadata); -``` - - - + + ```javascript + let metadata = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + + mediaMessage.setMetadata(metadata); + ``` + + + ```typescript + let metadata: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + + mediaMessage.setMetadata(metadata); + ``` + -### Add Caption(Text along with Media Message) +### Add Caption (Text along with Media Message) To send a caption with a media message, you can use the `setCaption` method and pass text to it. - -```javascript -let tags = ["starredMessage"]; - -mediaMessage.setTags(tags); -``` - - - - -```typescript -let caption: string = "Random Caption"; - -mediaMessage.setCaption(caption); -``` - - - + + ```javascript + let caption = "Random Caption"; + + mediaMessage.setCaption(caption); + ``` + + + ```typescript + let caption: string = "Random Caption"; + + mediaMessage.setCaption(caption); + ``` + ### Add Tags @@ -376,34 +464,30 @@ mediaMessage.setCaption(caption); To add a tag to a message you can use the `setTags()` method of the MediaMessage Class. The `setTags()` method accepts a list of tags. - -```javascript -let tags = ["starredMessage"]; - -mediaMessage.setTags(tags); -``` - - - - -```typescript -let tags: Array = ["starredMessage"]; - -mediaMessage.setTags(tags); -``` - - - + + ```javascript + let tags = ["starredMessage"]; + + mediaMessage.setTags(tags); + ``` + + + ```typescript + let tags: Array = ["starredMessage"]; + + mediaMessage.setTags(tags); + ``` + There are 2 ways you can send Media Messages using the CometChat SDK: -1. **By providing the File:** You can directly share the file object while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the `sendMediaMessage()` function. +### 1. By Providing the File -Getting file Object: You can use different React native packages for sending media messages. We demonstrate how to send images using CometChat. +You can directly share the file object while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the `sendMediaMessage()` function. + +**Getting the file Object:** You can use different React Native packages for sending media messages. We demonstrate how to send images using CometChat. - - ```javascript ImagePicker.showImagePicker(options, (response) => { if (response.didCancel) { @@ -434,107 +518,95 @@ if (response.didCancel) { } ``` - - - - - -```javascript -let receiverID = "UID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` + + ```javascript + let receiverID = "UID"; + let messageType = CometChat.MESSAGE_TYPE.FILE; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + this.state.mediaMsg, + messageType, + receiverType + ); + + CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + + + ```javascript + let receiverID = "GUID"; + let messageType = CometChat.MESSAGE_TYPE.FILE; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + this.state.mediaMsg, + messageType, + receiverType + ); + + CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + this.state.mediaMsg, + messageType, + receiverType + ); - + CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + this.state.mediaMsg, + messageType, + receiverType + ); + CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + The `MediaMessage` class constructor takes the following parameters: @@ -546,166 +618,351 @@ The `MediaMessage` class constructor takes the following parameters: | **messageType** | The type of the message that needs to be sent which in this case can be:
1.`CometChat.MESSAGE_TYPE.IMAGE`
2.`CometChat.MESSAGE_TYPE.VIDEO`
3.`CometChat.MESSAGE_TYPE.AUDIO`
4.`CometChat.MESSAGE_TYPE.FILE` | YES | | **receiverType** | The type of the receiver to whom the message is to be sent.
`1. CometChat.RECEIVER_TYPE.USER`
`2. CometChat.RECEIVER_TYPE.GROUP` | YES | -2. **By providing the URL of the File:** The second way to send media messages using the CometChat SDK is to provide the SDK with the URL of any file that is hosted on your servers or any cloud storage. To achieve this you will have to make use of the Attachment class. For more information, you can refer to the below code snippet: - - - -```javascript -let receiverID = "cometchat-uid-2"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); - -let file = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment = new CometChat.Attachment(file); - -mediaMessage.setAttachment(attachment); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); + +**On Success** — `console.log("Media message sent successfully", message)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "category": "message", + "type": "image", + "resource": "REACT_NATIVE-4_0_14-542c56fc-a1a6-4df4-a5e4-549f3cf17550-1771321970718", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771323061_1750099251_c35f9734fc20947b7456bbea68126f99.png", + "attachments": [ + { + "name": "1770616246_260562078_3832605b5c8a337ac672b0c60933d208.png", + "extension": "png", + "size": 2295572, + "mimeType": "image/png", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771323061_1750099251_c35f9734fc20947b7456bbea68126f99.png" + } + ], + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771323060, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771322968, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "tags": [] + }, + "entityType": "user" + } + }, + "moderation": { + "status": "pending" + } }, - (error) => { - console.log("error in sending message", error); - } -); -``` - - - - -```javascript -let receiverID = "cometchat-guid-1"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); - -let file = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment = new CometChat.Attachment(file); - -mediaMessage.setAttachment(attachment); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); + "id": "25189", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323060, + "role": "default", + "status": "online", + "tags": [] }, - (error) => { - console.log("error in sending message", error); - } -); + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771322968, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771323061, + "updatedAt": 1771323061 +} ``` - - - -```typescript -let receiverID: string = "cometchat-uid-2", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let file: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; +**On Failure** — `console.log("Media message sending failed with error", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in. Please log in before sending a message.", + "details": {} +} +``` + -let attachment: CometChat.Attachment = new CometChat.Attachment(file); +### 2. By Providing the URL of the File -mediaMessage.setAttachment(attachment); +The second way to send media messages using the CometChat SDK is to provide the SDK with the URL of any file that is hosted on your servers or any cloud storage. To achieve this you will have to make use of the Attachment class. For more information, you can refer to the below code snippet: -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); - }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); -``` + + + ```javascript + let receiverID = "cometchat-uid-2"; + let messageType = CometChat.MESSAGE_TYPE.IMAGE; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + + let file = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment = new CometChat.Attachment(file); + mediaMessage.setAttachment(attachment); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage) => { + console.log("message", mediaMessage); + }, + (error) => { + console.log("error in sending message", error); + } + ); + ``` + + + ```javascript + let receiverID = "cometchat-guid-1"; + let messageType = CometChat.MESSAGE_TYPE.IMAGE; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + + let file = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment = new CometChat.Attachment(file); + mediaMessage.setAttachment(attachment); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage) => { + console.log("message", mediaMessage); + }, + (error) => { + console.log("error in sending message", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "cometchat-uid-2", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); - - - -```typescript -let receiverID: string = "cometchat-guid-1", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let file: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; + let file: Object = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment: CometChat.Attachment = new CometChat.Attachment(file); + mediaMessage.setAttachment(attachment); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage: CometChat.MediaMessage) => { + console.log("message", mediaMessage); + }, + (error: CometChat.CometChatException) => { + console.log("error in sending message", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "cometchat-guid-1", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); -let attachment: CometChat.Attachment = new CometChat.Attachment(file); + let file: Object = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment: CometChat.Attachment = new CometChat.Attachment(file); + mediaMessage.setAttachment(attachment); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage: CometChat.MediaMessage) => { + console.log("message", mediaMessage); + }, + (error: CometChat.CometChatException) => { + console.log("error in sending message", error); + } + ); + ``` + + -mediaMessage.setAttachment(attachment); +When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); + +**On Success** — `console.log("message", mediaMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "category": "message", + "type": "image", + "resource": "REACT_NATIVE-4_0_14-542c56fc-a1a6-4df4-a5e4-549f3cf17550-1771321970718", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771323061_1750099251_c35f9734fc20947b7456bbea68126f99.png", + "attachments": [ + { + "name": "mario", + "extension": "png", + "mimeType": "image/png", + "url": "https://pngimg.com/uploads/mario/mario_PNG125.png" + } + ], + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771323060, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771322968, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "tags": [] + }, + "entityType": "user" + } + }, + "moderation": { + "status": "pending" + } }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); + "id": "25189", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323060, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771322968, + "role": "default", + "status": "offline", + "tags": [] + }, + "sentAt": 1771323061, + "updatedAt": 1771323061 +} ``` - - - - -When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. +**On Failure** — `console.log("error in sending message", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in. Please log in before sending a message.", + "details": {} +} +``` + ## Multiple Attachments in a Media Message Starting version 3.0.9 & above the SDK supports sending multiple attachments in a single media message. As in the case of a single attachment in a media message, there are two ways you can send Media Messages using the CometChat SDK: -1. **By providing an array of files:** You can now share an array of files while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, the files are uploaded to the CometChat servers & the URL of the files is sent in the success response of the `sendMediaMessage()` method. +### 1. By Providing an Array of Files -Getting the file Object: You can use different React native packages for sending media messages. We demonstrate how to send images using CometChat. +You can now share an array of files while creating an object of the MediaMessage class. When the media message is sent using the `sendMediaMessage()` method, the files are uploaded to the CometChat servers & the URL of the files is sent in the success response of the `sendMediaMessage()` method. + +**Getting the file Object:** You can use different React Native packages for sending media messages. We demonstrate how to send images using CometChat. - - ```javascript let options = { - selectionLimit: 0 + selectionLimit: 0 }; ImagePicker.showImagePicker(options, (response) => { if (response.didCancel) { @@ -758,302 +1015,387 @@ if (response.didCancel) { } ``` - - - - - -```javascript -let receiverID = "UID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - files, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let messageType = CometChat.MESSAGE_TYPE.FILE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - messageType, - receiverType -); - -CometChat.sendMediaMessage(mediaMessage).then( - (message) => { - console.log("Media message sent successfully", message); - }, - (error) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - messageType: string = CometChat.MESSAGE_TYPE.FILE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - this.state.mediaMsg, - messageType, - receiverType - ); - -CometChat.sendMediaMessage(mediaMessage).then( - (message: CometChat.MediaMessage) => { - console.log("Media message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("Media message sending failed with error", error); - } -); -``` + + ```javascript + let receiverID = "UID"; + let messageType = CometChat.MESSAGE_TYPE.FILE; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + files, + messageType, + receiverType + ); + + CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + + + ```javascript + let receiverID = "GUID"; + let messageType = CometChat.MESSAGE_TYPE.FILE; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + this.state.mediaMsg, + messageType, + receiverType + ); + + CometChat.sendMediaMessage(mediaMessage).then( + (message) => { + console.log("Media message sent successfully", message); + }, + (error) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "UID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + this.state.mediaMsg, + messageType, + receiverType + ); - + CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "GUID", + messageType: string = CometChat.MESSAGE_TYPE.FILE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + this.state.mediaMsg, + messageType, + receiverType + ); + CometChat.sendMediaMessage(mediaMessage).then( + (message: CometChat.MediaMessage) => { + console.log("Media message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("Media message sending failed with error", error); + } + ); + ``` + The `MediaMessage` class constructor takes the following parameters: -| | | +| Parameter | Description | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **receiverId** | The `UID` or `GUID` of the recipient. | | **files** | An array of files. | | **messageType** | The type of the message that needs to be sent which in this case can be:
1.`CometChat.MESSAGE_TYPE.IMAGE`
2.`CometChat.MESSAGE_TYPE.VIDEO`
3.`CometChat.MESSAGE_TYPE.AUDIO`
4.`CometChat.MESSAGE_TYPE.FILE` | | **receiverType** | The type of the receiver to whom the message is to be sent.
`1. CometChat.RECEIVER_TYPE.USER`
`2. CometChat.RECEIVER_TYPE.GROUP` | -2. **By providing the URL of the multiple files:** The second way to send multiple attachments in a single media message using the CometChat SDK is to provide the SDK with the URL of multiple files that are hosted on your servers or any cloud storage. To achieve this you will have to make use of the Attachment class. For more information, you can refer to the below code snippet: - - - -```javascript -let receiverID = "cometchat-uid-2"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); - -let attachment1 = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment2 = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; - -let attachments = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); +### 2. By Providing the URL of Multiple Files -mediaMessage.setAttachments(attachments); +The second way to send multiple attachments in a single media message using the CometChat SDK is to provide the SDK with the URL of multiple files that are hosted on your servers or any cloud storage. To achieve this you will have to make use of the Attachment class. For more information, you can refer to the below code snippet: -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); - }, - (error) => { - console.log("error in sending message", error); - } -); -``` - - + + + ```javascript + let receiverID = "cometchat-uid-2"; + let messageType = CometChat.MESSAGE_TYPE.IMAGE; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + + let attachment1 = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment2 = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", + }; + + let attachments = []; + attachments.push(new CometChat.Attachment(attachment1)); + attachments.push(new CometChat.Attachment(attachment2)); + + mediaMessage.setAttachments(attachments); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage) => { + console.log("message", mediaMessage); + }, + (error) => { + console.log("error in sending message", error); + } + ); + ``` + + + ```javascript + let receiverID = "cometchat-guid-1"; + let messageType = CometChat.MESSAGE_TYPE.IMAGE; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let mediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); + + let attachment1 = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment2 = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", + }; + + let attachments = []; + attachments.push(new CometChat.Attachment(attachment1)); + attachments.push(new CometChat.Attachment(attachment2)); + + mediaMessage.setAttachments(attachments); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage) => { + console.log("message", mediaMessage); + }, + (error) => { + console.log("error in sending message", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "cometchat-uid-2", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.USER, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); - -```javascript -let receiverID = "cometchat-guid-1"; -let messageType = CometChat.MESSAGE_TYPE.IMAGE; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let mediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType -); - -let attachment1 = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; + let attachment1: Object = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment2: Object = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", + }; + + let attachments: Array = []; + attachments.push(new CometChat.Attachment(attachment1)); + attachments.push(new CometChat.Attachment(attachment2)); + + mediaMessage.setAttachments(attachments); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage: CometChat.MediaMessage) => { + console.log("message", mediaMessage); + }, + (error: CometChat.CometChatException) => { + console.log("error in sending message", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "cometchat-guid-1", + messageType: string = CometChat.MESSAGE_TYPE.IMAGE, + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( + receiverID, + "", + messageType, + receiverType + ); -let attachment2 = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; + let attachment1: Object = { + name: "mario", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/mario/mario_PNG125.png", + }; + + let attachment2: Object = { + name: "jaguar", + extension: "png", + mimeType: "image/png", + url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", + }; + + let attachments: Array = []; + attachments.push(new CometChat.Attachment(attachment1)); + attachments.push(new CometChat.Attachment(attachment2)); + + mediaMessage.setAttachments(attachments); + + CometChat.sendMediaMessage(mediaMessage).then( + (mediaMessage: CometChat.MediaMessage) => { + console.log("message", mediaMessage); + }, + (error: CometChat.CometChatException) => { + console.log("error in sending message", error); + } + ); + ``` + + -let attachments = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); +When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. -mediaMessage.setAttachments(attachments); +You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add metadata, caption and tags respectively in exactly the same way as it is done while sending a single file or attachment in a Media Message. -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); + +**On Success** — `console.log("message", mediaMessage)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "image", + "receiverType": "user", + "category": "message", + "data": { + "category": "message", + "type": "image", + "resource": "REACT_NATIVE-4_0_14-542c56fc-a1a6-4df4-a5e4-549f3cf17550-1771321970718", + "url": "https://data-in.cometchat.io/2748663902141719/media/1771323061_1750099251_c35f9734fc20947b7456bbea68126f99.png", + "attachments": [ + { + "name": "mario", + "extension": "png", + "mimeType": "image/png", + "url": "https://pngimg.com/uploads/mario/mario_PNG125.png" + }, + { + "name": "jaguar", + "extension": "png", + "mimeType": "image/png", + "url": "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png" + } + ], + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771323060, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771322968, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "tags": [] + }, + "entityType": "user" + } + }, + "moderation": { + "status": "pending" + } }, - (error) => { - console.log("error in sending message", error); - } -); -``` - -
- - -```typescript -let receiverID: string = "cometchat-uid-2", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.USER, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let attachment1: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment2: Object = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; - -let attachments: Array = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); - -mediaMessage.setAttachments(attachments); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); + "id": "25189", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323060, + "role": "default", + "status": "online", + "tags": [] }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); -``` - - - - -```typescript -let receiverID: string = "cometchat-guid-1", - messageType: string = CometChat.MESSAGE_TYPE.IMAGE, - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - mediaMessage: CometChat.MediaMessage = new CometChat.MediaMessage( - receiverID, - "", - messageType, - receiverType - ); - -let attachment1: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; - -let attachment2: Object = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; - -let attachments: Array = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); - -mediaMessage.setAttachments(attachments); - -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771322968, + "role": "default", + "status": "offline", + "tags": [] }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); + "sentAt": 1771323061, + "updatedAt": 1771323061 +} ``` - - -
- -When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. - -You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add metadata, caption and tags respectively in exactly the same way as it is done while sending a single file or attachment in a Media Message. +**On Failure** — `console.log("error in sending message", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in. Please log in before sending a message.", + "details": {} +} +``` + ## Custom Message @@ -1061,45 +1403,41 @@ You can use the `setMetadata()`, `setCaption()` & `setTags()` methods to add met CometChat allows you to send custom messages which are neither text nor media messages. -In order to send a custom message, you need to use the `sendCustomMessage()` method. - -The `sendCustomMessage()` method takes an object of the `CustomMessage` which can be obtained using the below constructor. +In order to send a custom message, you need to use the `sendCustomMessage()` method. The `sendCustomMessage()` method takes an object of the `CustomMessage` which can be obtained using the below constructor. - -```javascript -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); -``` - - - - -```javascript -let customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); -``` - - - + + ```javascript + let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + ``` + + + ```typescript + let customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + ``` + -The above constructor, helps you create a custom message with the message type set to whatever is passed to the constructor and the category set to `custom`. +The above constructor helps you create a custom message with the message type set to whatever is passed to the constructor and the category set to `custom`. The parameters involved are: -1. `receiverId` - The unique ID of the user or group to which the message is to be sent. -2. `receiverType` - Type of the receiver i.e user or group -3. `customType` - custom message type that you need to set -4. `customData` - The data to be passed as the message in the form of a JSON Object. +| Parameter | Description | +| -------------- | ------------------------------------------------------------------------------ | +| `receiverId` | The unique ID of the user or group to which the message is to be sent | +| `receiverType` | Type of the receiver i.e user or group | +| `customType` | Custom message type that you need to set | +| `customData` | The data to be passed as the message in the form of a JSON Object | You can also use the subType field of the `CustomMessage` class to set a specific type for the custom message. This can be achieved using the `setSubtype()` method. @@ -1108,146 +1446,247 @@ You can also use the subType field of the `CustomMessage` class to set a specifi To add a tag to a message you can use the `setTags()` method of the CustomMessage Class. The `setTags()` method accepts a list of tags. - -```javascript -let tags = ["starredMessage"]; - -customMessage.setTags(tags); -``` - - - - -```typescript -let tags: Array = ["starredMessage"]; - -customMessage.setTags(tags); -``` - - - + + ```javascript + let tags = ["starredMessage"]; + + customMessage.setTags(tags); + ``` + + + ```typescript + let tags: Array = ["starredMessage"]; + + customMessage.setTags(tags); + ``` + Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. - -```javascript -let receiverID = "UID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` + + ```javascript + let receiverID = "UID"; + let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + let customType = "location"; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + + CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```javascript + let receiverID = "GUID"; + let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + let customType = "location"; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + + CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "UID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); - + CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "GUID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); - -```javascript -let receiverID = "GUID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` + CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + -
+The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups. - -```typescript -let receiverID: string = "UID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", +On success, you will receive an object of the `CustomMessage` class. + + +**On Success** — `console.log("custom message sent successfully", message)` returns: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-3", + "type": "location", + "receiverType": "user", + "category": "custom", + "customData": { + "latitude": "50.6192171633316", + "longitude": "-72.68182268750002" }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); + "data": { + "customData": { + "latitude": "50.6192171633316", + "longitude": "-72.68182268750002" + }, + "text": "Sent a custom message", + "resource": "REACT_NATIVE-4_0_14-542c56fc-a1a6-4df4-a5e4-549f3cf17550-1771321970718", + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771323089, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "status": "offline", + "role": "default", + "lastActiveAt": 1771322968, + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "tags": [] + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "pending" + } }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", + "id": "25190", + "conversationId": "cometchat-uid-2_user_cometchat-uid-3", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-2", + "name": "George Alan", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp", + "lastActiveAt": 1771323089, + "role": "default", + "status": "online", + "tags": [] }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-3", + "name": "Nancy Grace", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp", + "lastActiveAt": 1771322968, + "role": "default", + "status": "offline", + "tags": [] }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); + "sentAt": 1771323234, + "updatedAt": 1771323234, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } } -); +} ``` - - -
- -The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups. - -On success, you will receive an object of the `CustomMessage` class. +**On Failure** — `console.log("custom message sending failed with error", error)` returns: +```json +{ + "code": "ERR_NOT_LOGGED_IN", + "name": "Not logged in", + "message": "No user is currently logged in. Please log in before sending a message.", + "details": {} +} +``` + ### Update Conversation @@ -1256,251 +1695,266 @@ On success, you will receive an object of the `CustomMessage` class. By default, a custom message will update the last message of a conversation. If you wish to not update the last message of the conversation when a custom message is sent, please use `shouldUpdateConversation(value: boolean)` method of the Custom Message. - -```javascript -let receiverID = "UID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -customMessage.shouldUpdateConversation(false); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -customMessage.shouldUpdateConversation(false); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -customMessage.shouldUpdateConversation(false); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -customMessage.shouldUpdateConversation(false); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); -``` + + ```javascript + let receiverID = "UID"; + let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + let customType = "location"; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + + customMessage.shouldUpdateConversation(false); + CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```javascript + let receiverID = "GUID"; + let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + let customType = "location"; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + + customMessage.shouldUpdateConversation(false); + CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "UID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); - + customMessage.shouldUpdateConversation(false); + CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "GUID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + customMessage.shouldUpdateConversation(false); + CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + ### Custom Notification Body -*How can i customise the notification body of custom message?* +*How can I customize the notification body of a custom message?* -To add a custom notification body for `Push, Email & SMS` notification of a custom message you can use the `setConversationText(text: string)` method of Custom Message class. +To add a custom notification body for `Push, Email & SMS` notification of a custom message you can use the `setConversationText(text: string)` method of the CustomMessage class. - -```javascript -let receiverID = "UID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.USER; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -customMessage.setConversationText("Custom notification body"); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - - -```javascript -let receiverID = "GUID"; -let customData = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; -let customType = "location"; -let receiverType = CometChat.RECEIVER_TYPE.GROUP; -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); - -customMessage.setConversationText("Custom notificatoin body"); -CometChat.sendCustomMessage(customMessage).then( - (message) => { - console.log("custom message sent successfully", message); - }, - (error) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "UID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.USER, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -customMessage.setConversationText("Custom notification body"); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); -``` - - - - -```typescript -let receiverID: string = "GUID", - customData: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", - }, - customType: string = "location", - receiverType: string = CometChat.RECEIVER_TYPE.GROUP, - customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData - ); - -customMessage.setConversationText("Custom notification body"); -CometChat.sendCustomMessage(customMessage).then( - (message: CometChat.CustomMessage) => { - console.log("custom message sent successfully", message); - }, - (error: CometChat.CometChatException) => { - console.log("custom message sending failed with error", error); - } -); -``` + + ```javascript + let receiverID = "UID"; + let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + let customType = "location"; + let receiverType = CometChat.RECEIVER_TYPE.USER; + let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + + customMessage.setConversationText("Custom notification body"); + CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```javascript + let receiverID = "GUID"; + let customData = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }; + let customType = "location"; + let receiverType = CometChat.RECEIVER_TYPE.GROUP; + let customMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + + customMessage.setConversationText("Custom notification body"); + CometChat.sendCustomMessage(customMessage).then( + (message) => { + console.log("custom message sent successfully", message); + }, + (error) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "UID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.USER, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); - + customMessage.setConversationText("Custom notification body"); + CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + + + ```typescript + let receiverID: string = "GUID", + customData: Object = { + latitude: "50.6192171633316", + longitude: "-72.68182268750002", + }, + customType: string = "location", + receiverType: string = CometChat.RECEIVER_TYPE.GROUP, + customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( + receiverID, + receiverType, + customType, + customData + ); + customMessage.setConversationText("Custom notification body"); + CometChat.sendCustomMessage(customMessage).then( + (message: CometChat.CustomMessage) => { + console.log("custom message sent successfully", message); + }, + (error: CometChat.CometChatException) => { + console.log("custom message sending failed with error", error); + } + ); + ``` + - -It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/react-native/interactive-messages) - +It is also possible to send interactive messages from CometChat. To learn more, see [Interactive Messages](/sdk/react-native/interactive-messages). + + + + - Use appropriate message types (`TEXT`, `IMAGE`, `VIDEO`, `AUDIO`, `FILE`) for media messages + - Add metadata to messages when you need to pass additional context (e.g., location, user preferences) + - Use tags to categorize messages for easier filtering and retrieval + - Set `shouldUpdateConversation(false)` for background or system-level custom messages that shouldn't appear in conversation lists + - Use `setConversationText()` to provide meaningful notification text for custom messages + + + - **Message not sending:** Ensure the user is logged in and CometChat is initialized + - **Media upload fails:** Check file size limits and ensure the file object has correct `name`, `type`, and `uri` properties + - **Custom message not appearing:** Verify the receiver UID/GUID is correct and the receiver type matches + - **Notifications not showing custom text:** Make sure `setConversationText()` is called before sending the message + + + +## Next Steps + + + + Listen for real-time messages and fetch missed messages + + + Edit previously sent messages + + + Send forms, cards, and custom interactive messages + + + Show real-time typing status in conversations + + diff --git a/sdk/react-native/session-timeout.mdx b/sdk/react-native/session-timeout.mdx index 5a6f3e420..5de98331f 100644 --- a/sdk/react-native/session-timeout.mdx +++ b/sdk/react-native/session-timeout.mdx @@ -1,9 +1,8 @@ --- title: "Session Timeout Flow" +description: "Understand how CometChat Calls SDK handles idle session timeouts — automatic call termination, user prompts, and the onSessionTimeout event (v4.2.0+)." --- - - Available since v4.2.0 ## Overview @@ -21,6 +20,10 @@ CometChat Calls SDK provides a mechanism to handle session timeouts for idle par This feature helps manage inactive call sessions and prevents unnecessary resource usage. The idle timeout period ensures that participants don't accidentally remain in abandoned call sessions. + +You can customize the idle timeout period using `setIdleTimeoutPeriod(seconds)` in the `CallSettingsBuilder`. See the [Call Session settings](/sdk/react-native/direct-call#call-settings) for details. + + ### Session Timeout Flow @@ -32,3 +35,16 @@ This feature helps manage inactive call sessions and prevents unnecessary resour The `onSessionTimeout` event is triggered when the call automatically terminates due to session timeout, as illustrated in the diagram above. + +--- + +## Next Steps + + + + Start and manage call sessions with full configuration options + + + Implement a complete calling experience with incoming and outgoing call UI + + \ No newline at end of file diff --git a/sdk/react-native/setup-sdk.mdx b/sdk/react-native/setup-sdk.mdx index b33a05c52..ecb16a896 100644 --- a/sdk/react-native/setup-sdk.mdx +++ b/sdk/react-native/setup-sdk.mdx @@ -1,16 +1,31 @@ --- title: "Setup" +description: "Install the CometChat React Native SDK, configure dependencies and permissions, and initialize CometChat in your application." --- + +**Quick Reference** - Install and initialize in three steps: +```javascript +// 1. Install dependencies +// npm i @cometchat/chat-sdk-react-native @react-native-async-storage/async-storage + +// 2. Initialize CometChat (call once on app startup) +const appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion("REGION") + .autoEstablishSocketConnection(true) + .build(); +await CometChat.init("APP_ID", appSetting); +``` + -Migrating app version from v3 to v4 ? +**Migrating from v3 to v4?** Skip the create new app step. Your existing v3 app can be migrated to v4. -Follow steps mentioned in **Add the CometChat dependency** section below to upgrade to latest version of v4 - +Follow the steps mentioned in the [Add the CometChat Dependency](#add-the-cometchat-dependency) section below to upgrade to the latest version of v4. ## Get your Application Keys @@ -22,207 +37,242 @@ Follow steps mentioned in **Add the CometChat dependency** section below to upgr ## Add the CometChat Dependency -Install the package as NPM module: +Install the package as an NPM module: - -```bash -npm i @cometchat/chat-sdk-react-native -``` - - - + + ```bash + npm i @cometchat/chat-sdk-react-native + ``` + + + ```bash + yarn add @cometchat/chat-sdk-react-native + ``` + -**In order to integrate the CometChat React Native SDK, you need to install one more dependencies** +In order to integrate the CometChat React Native SDK, you need to install one more dependency. -1. Async-Storage: +### Async-Storage - -```javascript -npm install @react-native-async-storage/async-storage -``` - - - + + ```bash + npm install @react-native-async-storage/async-storage + ``` + + + ```bash + yarn add @react-native-async-storage/async-storage + ``` + ## Calling Component Configuration For `@cometchat/calls-sdk-react-native`, please make sure you add the following additional dependencies & permissions. - - +### Required Dependencies + ```json { -"@cometchat/chat-sdk-react-native": "^4.0.18", -"@react-native-async-storage/async-storage": "^1.23.1", -"@react-native-community/netinfo": "^11.3.1", // for react-native 0.63 & above. -"@react-native-community/netinfo": "6.1.0", // for react-native below 0.63 -"react-native-background-timer": "^2.4.1", -"react-native-callstats": "^3.73.7", -"react-native-webrtc": "^1.106.1" + "@cometchat/chat-sdk-react-native": "^4.0.18", + "@react-native-async-storage/async-storage": "^1.23.1", + "@react-native-community/netinfo": "^11.3.1", // for react-native 0.63 & above + "@react-native-community/netinfo": "6.1.0", // for react-native below 0.63 + "react-native-background-timer": "^2.4.1", + "react-native-callstats": "^3.73.7", + "react-native-webrtc": "^1.106.1" } ``` - - - - -#### Permissions: - -**Android:** +### Permissions - -```xml - - - - - -``` - - - + + Add the following permissions to your `AndroidManifest.xml`: + + ```xml + + + + + + ``` + + + Add the following keys to your `Info.plist`: + + ```xml + NSCameraUsageDescription + This is for Camera permission + NSMicrophoneUsageDescription + This is for Mic permission + ``` + -**iOS:** - - - -```xml -NSCameraUsageDescription -This is for Camera permission -NSMicrophoneUsageDescription -This is for Mic permission -``` - - +### Platform-Specific Configuration + + + + Go to the `./android` folder and open the **project level** `build.gradle` file. Add all repository URLs in the `repositories` block under the `allprojects` section. + + ```gradle + allprojects { + repositories { + maven { + url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/" + } + } + } + ``` + + Also in the same file, in the `buildscript` section in the `ext` block, make sure you have set **minSdkVersion** to **24**. + + ```gradle + buildscript { + ext { + buildToolsVersion = "29.0.2" + minSdkVersion = 24 + compileSdkVersion = 29 + targetSdkVersion = 29 + } + } + ``` + + + Please update the minimum target version in the Podfile. Go to the `./ios` folder and open the Podfile. In the Podfile, update the platform version to `11.0`: + + ```ruby + platform :ios, '11.0' + ``` + + Open the `ios/App` folder and run `pod install`. This will create an `App.xcworkspace` file. Open this and run the app. + + - +## Initialize CometChat -#### Android: +The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters: -Goto `./android` folder and open **project level** `build.gradle` file and add all repository URLs in the `repositories` block under the `allprojects` section. +| Parameter | Description | +| ------------ | ---------------------------------------------------------------------------------------------------------- | +| `appID` | Your CometChat App ID | +| `appSettings`| An object of the `AppSettings` class created using the `AppSettingsBuilder` class. The region is mandatory. | - - -```java -allprojects { -repositories { - maven { - url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/" - } -} -} -``` - - +The `AppSettings` class allows you to configure the following settings: - +| Setting | Description | +|---------|-------------| +| **Region** | The region where your app was created (mandatory). Set using `setRegion()` | +| **Presence Subscription** | Represents the subscription type for user presence (real-time online/offline status). See [User Presence](/sdk/react-native/user-presence) | +| **autoEstablishSocketConnection(boolean)** | When set to `true`, the SDK manages the web-socket connection internally. When set to `false`, you manage the connection manually. Default: `true`. See [Managing Web-Socket connections manually](/sdk/react-native/managing-web-sockets-connections-manually) | +| **overrideAdminHost(adminHost: string)** | Uses a custom admin URL instead of the default. Used for dedicated CometChat deployments | +| **overrideClientHost(clientHost: string)** | Uses a custom client URL instead of the default. Used for dedicated CometChat deployments | -Also in the same file in `buildscript` section in `ext` block make sure you have set **minSdkVersion** to **24.** +You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `App.tsx` file. - -```gradle -buildscript { - ext { - buildToolsVersion = "29.0.2" - minSdkVersion = 24 - compileSdkVersion = 29 - targetSdkVersion = 29 - } -} -``` - - - + + ```javascript + let appID = "APP_ID"; + let region = "REGION"; + + // Build app settings with presence subscription and auto socket connection + let appSetting = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + + // Initialize CometChat — call once on app startup + CometChat.init(appID, appSetting).then( + () => { + console.log("Initialization completed successfully"); + }, + (error) => { + console.log("Initialization failed with error:", error); + } + ); + ``` + + + ```typescript + let appID: string = "APP_ID", + region: string = "APP_REGION", + + // Build app settings with presence subscription and auto socket connection + let appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() + .subscribePresenceForAllUsers() + .setRegion(region) + .autoEstablishSocketConnection(true) + .build(); + + // Initialize CometChat — call once on app startup + CometChat.init(appID, appSetting).then( + (initialized: boolean) => { + console.log("Initialization completed successfully", initialized); + }, + (error: CometChat.CometChatException) => { + console.log("Initialization failed with error:", error); + } + ); + ``` + -#### iOS: - -Please update the minimum target version in the Podfile. Goto ./ios folder and open the Podfile. In the Podfile update the platform version to `11.0.` + +Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` with your **App Region** in the above code. + - - + +**On Success** — `console.log("Initialization completed successfully")` returns: ``` -platform :ios, '11.0' +Initialization completed successfully ``` - - - - -Open the `ios/App` folder and run `pod install` this will create an `App.xcworkspace` open this and run the app. - -## Initialize CometChat - -The `init()` method initialises the settings required for CometChat. The `init()` method takes the below parameters: - -1. appID - You CometChat App ID -2. appSettings - An object of the AppSettings class can be created using the AppSettingsBuilder class. The region field is mandatory and can be set using the `setRegion()` method. - -The `AppSettings` class allows you to configure two settings: - -* **Region**: The region where your app was created. -* [Presence Subscription](/sdk/react-native/user-presence): Represents the subscription type for user presence (real-time online/offline status) -* **autoEstablishSocketConnection(boolean value)**: This property takes a boolean value which when set to true informs the SDK to manage the web-socket connection internally. If set to false, it informs the SDK that the web-socket connection will be managed manually. The default value for this parameter is true. For more information on this, please check the [Managing Web-Socket connections manually](/sdk/react-native/managing-web-sockets-connections-manually) section. The default value for this property is **true.** -* **overrideAdminHost(adminHost: string)**: This method takes the admin URL as input and uses this admin URL instead of the default admin URL. This can be used in case of dedicated deployment of CometChat. -* **overrideClientHost(clientHost: string)**: This method takes the client URL as input and uses this client URL instead of the default client URL. This can be used in case of dedicated deployment of CometChat. - -You need to call `init()` before calling any other method from CometChat. We suggest you call the `init()` method on app startup, preferably in the `index.js` file. - - - -```javascript -let appID = "APP_ID"; -let region = "REGION"; -let appSetting = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); -CometChat.init(appID, appSetting).then( - () => { - console.log("Initialization completed successfully"); - }, - (error) => { - console.log("Initialization failed with error:", error); - } -); -``` - - - - -```javascript -let appID: string = "APP_ID", - region: string = "APP_REGION", - appSetting: CometChat.AppSettings = new CometChat.AppSettingsBuilder() - .subscribePresenceForAllUsers() - .setRegion(region) - .autoEstablishSocketConnection(true) - .build(); -CometChat.init(appID, appSetting).then( - (initialized: boolean) => { - console.log("Initialization completed successfully", initialized); - }, - (error: CometChat.CometChatException) => { - console.log("Initialization failed with error:", error); - } -); +**On Failure** — `console.log("Initialization failed with error:", error)` returns: +```json +{ + "code": "ERR_INVALID_APP_ID", + "name": "Invalid App ID", + "message": "The App ID provided is incorrect. Please verify your App ID from the CometChat Dashboard.", + "details": {} +} ``` - - - - - -Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` with your **App Region** in the above code. - -| Parameter | Description | -| ---------- | ----------------------------------- | -| appID | CometChat App ID | -| appSetting | An object of the AppSettings class. | + + + + + - Always call `init()` before any other CometChat method + - Call `init()` on app startup, preferably in `App.tsx` + - Use `autoEstablishSocketConnection(true)` unless you have a specific need to manage connections manually + - For dedicated deployments, use `overrideAdminHost` and `overrideClientHost` to point to your custom URLs + + + - **Initialization fails:** Verify your App ID and Region are correct + - **Network errors:** Check internet connectivity and firewall settings + - **Calling not working:** Verify all calling dependencies are installed and permissions are granted + - **iOS build fails:** Run `pod install` in the `ios` directory after adding dependencies + - **Android build fails:** Ensure `minSdkVersion` is set to 24 and the CometChat Maven repository is added + + + +## Next Steps + + + + Register and log in users with Auth Key or Auth Token + + + Understand the fundamental building blocks of CometChat + + + Start sending text, media, and custom messages + + + Add pre-built UI components to your app + + diff --git a/sdk/react-native/standalone-calling.mdx b/sdk/react-native/standalone-calling.mdx index 5010c4e98..eabf1d10f 100644 --- a/sdk/react-native/standalone-calling.mdx +++ b/sdk/react-native/standalone-calling.mdx @@ -1,7 +1,29 @@ --- title: "Standalone Calling" +description: "Implement audio and video calling using only the CometChat Calls SDK, without the Chat SDK — ideal for apps that need calling without full chat infrastructure." --- + +**Quick Reference** - Generate token and start a standalone call session: + +```javascript +// Generate call token (auth token from REST API, not Chat SDK) +const callToken = await CometChatCalls.generateToken(sessionId, userAuthToken); + +// Configure and render +const callSettings = new CometChatCalls.CallSettingsBuilder() + .enableDefaultLayout(true) + .setIsAudioOnlyCall(false) + .build(); + +// +``` + + + +**Available via:** SDK | UI Kits + + ## Overview This section demonstrates how to implement calling functionality using only the CometChat Calls SDK, without requiring the Chat SDK. This is ideal for applications that need video/audio calling capabilities without the full chat infrastructure. @@ -23,6 +45,10 @@ You can obtain the auth token using one of these REST API endpoints: - [Create Auth Token](/rest-api/auth-tokens/create) — Creates a new auth token for a user - [Get Auth Token](/rest-api/auth-tokens/get) — Retrieves an existing auth token + +Auth tokens grant access to call sessions on behalf of a user. Never expose auth tokens in client-side code in production. Use a secure backend to generate and deliver tokens to your app. + + For testing or POC purposes, you can create an auth token directly from the [CometChat Dashboard](https://app.cometchat.com). Navigate to **Users & Groups → Users**, select a user, and click **+ Create Auth Token**. @@ -81,6 +107,20 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( | `sessionId` | A unique session ID for the call. Generate this yourself or use a shared ID for participants to join the same call. | | `userAuthToken` | The user auth token obtained from the CometChat REST API. | + +**On Success** — `generateToken()` returns a `GenerateToken` object containing the session ID and JWT token: + + + +**GenerateToken Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sessionId` | string | Unique identifier for the call session | `"v1.in.2748663902141719.1772095292a49c6a5198e07f9096447749e87124204d95cfc8"` | +| `token` | string | JWT token for authenticating the call session | `"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImNjcHJvX2p3dF9yczI1Nl9rZXkxIn0..."` | + + + ## Start Call Session Use the `CometChatCalls.Component` to render the call UI. This component requires a call token (generated in the previous step) and a `CallSettings` object that configures the call UI and behavior. @@ -343,6 +383,10 @@ useEffect(() => {
+ +Always remove call event listeners when the component unmounts using `CometChatCalls.removeCallEventListener(listenerId)`. Failing to remove listeners can cause memory leaks and duplicate event handling. + + ### Events | Event | Description | @@ -360,6 +404,94 @@ useEffect(() => { | `onScreenShareStopped()` | Invoked when the local user stops sharing a screen. | | `onError(error)` | Invoked when an error occurs during the call session. | + +**On Event** — `onUserJoined` returns a user object when a participant joins the call: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `id` | string | Internal session participant ID | `"cd530243"` | +| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | +| `isVideoMuted` | boolean | Whether user's video is muted | `true` | +| `isAudioMuted` | boolean | Whether user's audio is muted | `false` | +| `isLocalUser` | boolean | Whether this is the local user | `false` | + + + + +**On Event** — `onUserLeft` returns a user object when a participant leaves the call: + + + +**User Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `name` | string | Display name of the user | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `id` | string | Internal session participant ID | `"cd530243"` | +| `joinedAt` | string | Unix timestamp when user joined (as string) | `"1772095303043"` | +| `isVideoMuted` | boolean | Whether user's video was muted | `true` | +| `isAudioMuted` | boolean | Whether user's audio was muted | `false` | + + + + +**On Event** — `onUserListUpdated` returns an array of all current participants in the call: + + + +**User Array:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of user objects | [See below ↓](#on-user-list-updated-user-object) | + + + +**User Object (each item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | + + + + +**On Event** — `onAudioModesUpdated` returns an array of available audio output modes: + + + +**Audio Modes Array:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of audio mode objects | [See below ↓](#on-audio-modes-updated-mode-object) | + + + +**Audio Mode Object (each item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Type of audio output device | `"SPEAKER"` | +| `selected` | boolean | Whether this mode is currently selected | `true` | + + + + +**On Event** — `onCallSwitchedToVideo` is invoked when an audio call is upgraded to video. This event may not include additional data. + + ## End Call Session To end the call session and release all media resources (camera, microphone, network connections), call `CometChatCalls.endSession()` in the `onCallEndButtonPressed()` callback. @@ -549,6 +681,28 @@ CometChatCalls.getAudioOutputModes().then(
+ +**On Success** — `getAudioOutputModes()` returns an object containing an array of available audio modes: + + + +**Response Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `modes` | array | Array of available audio output modes | [See below ↓](#get-audio-modes-mode-object) | + + + +**Mode Object (each item in `modes` array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Type of audio output device | `"SPEAKER"` | +| `selected` | boolean | Whether this mode is currently selected | `true` | + + + ### End Call Terminates the current call session and releases all media resources (camera, microphone, network connections). After calling this method, the call view should be closed. @@ -569,3 +723,62 @@ CometChatCalls.endSession();
+ +## Best Practices + + + + Call tokens are session-specific and time-limited. Generate them right before starting the call session rather than caching them for extended periods. This ensures the token is fresh and reduces the chance of token expiry errors. + + + All participants who need to join the same call must use the same `sessionId` when generating their call tokens. Share this ID through your backend or signaling mechanism so both parties can join the same session. + + + Since standalone calling uses REST API auth tokens instead of the Chat SDK login flow, ensure tokens are generated server-side and delivered securely to the client. Never hardcode auth tokens in your app bundle. + + + Always remove call event listeners in your component's cleanup function (e.g., the return function of `useEffect`). Orphaned listeners can cause memory leaks, duplicate event handling, and unexpected behavior when navigating between screens. + + + The `CometChatCalls.Component` should be rendered inside a `View` with `height: '100%'`, `width: '100%'`, and `position: 'relative'`. This ensures the call UI fills the screen correctly and overlays render in the right position. + + + +## Troubleshooting + + + + Verify the auth token is valid and hasn't expired. Auth tokens obtained from the REST API or Dashboard have an expiry — generate a fresh one if needed. Also confirm the `sessionId` is a non-empty string. + + + Ensure the `CometChatCalls.Component` is wrapped in a `View` with explicit dimensions (`height: '100%'`, `width: '100%'`). Also confirm that both `callSettings` and `callToken` props are provided and not `null` or `undefined`. + + + Both participants must use the exact same `sessionId` when generating their call tokens. Double-check that the session ID is being shared correctly between devices. + + + Check that the listener is registered before the call session starts. If using `addCallEventListener`, ensure the `listenerId` is unique and hasn't been overwritten by another registration. Also verify that the Calls SDK has been initialized via `CometChatCalls.init()`. + + + Check device permissions for camera and microphone. On React Native, request `CAMERA` and `RECORD_AUDIO` permissions on Android, and add `NSCameraUsageDescription` and `NSMicrophoneUsageDescription` to `Info.plist` on iOS. + + + +--- + +## Next Steps + + + + Install dependencies, configure permissions, and initialize the Calls SDK + + + Record call sessions for playback and compliance + + + Customize the main video container and participant tiles + + + Full call session management with the Chat SDK integration + + \ No newline at end of file diff --git a/sdk/react-native/threaded-messages.mdx b/sdk/react-native/threaded-messages.mdx index 02b405a14..5bc3abe14 100644 --- a/sdk/react-native/threaded-messages.mdx +++ b/sdk/react-native/threaded-messages.mdx @@ -1,30 +1,62 @@ --- title: "Threaded Messages" +description: "Send, receive, and fetch threaded messages (replies) in user and group conversations using the CometChat React Native SDK." --- +{/* TL;DR for Agents and Quick Reference */} + +**Quick Reference** - Send a threaded message and fetch thread replies: +```javascript +// Send a text message in a thread +let textMessage = new CometChat.TextMessage("UID", "Hello", CometChat.RECEIVER_TYPE.USER); +textMessage.setParentMessageId(100); +CometChat.sendMessage(textMessage).then( + message => console.log("Sent:", message), + err => console.log("Error:", err) +); + +// Fetch messages for a thread +let messagesRequest = new CometChat.MessagesRequestBuilder() + .setLimit(30) + .setParentMessageId(100) + .build(); +messagesRequest.fetchPrevious().then( + messages => console.log("Thread messages:", messages), + error => console.log("Error:", error) +); +``` + -Messages that are started from a particular message are called Threaded messages or simply threads. Each Thread is attached to a message which is the Parent message for that thread. + +**Available via:** [SDK](/sdk/react-native/threaded-messages) | [REST API](/rest-api/messages/list-threaded-messages) | [UI Kits](/ui-kit/react-native/core-features#threaded-conversations) + + +Messages that are started from a particular message are called Threaded Messages or simply threads. Each thread is attached to a message which is the parent message for that thread. ## Send Message in a Thread -As mentioned in the [Send a Message](/sdk/react-native/send-message) section. You can either send a message to a User or a Group based on the `receiverType` and the UID/GUID specified for the message. A message can belong to either of the below types: +As mentioned in the [Send a Message](/sdk/react-native/send-message) section, you can either send a message to a user or a group based on the `receiverType` and the UID/GUID specified for the message. A message can belong to any of the following types: 1. Text Message 2. Media Message -3. Custom Message. +3. Custom Message + +Any of the above messages can be sent in a thread. A thread is identified based on the parent message, so while sending a message the `parentMessageId` must be set to indicate that the message belongs to the thread with the specified `parentMessageId`. -Any of the above messages can be sent in a thread. As mentioned, a thread is identified based on the Parent message. So while sending a message the `parentMessageId` must be set for the message to indicate that the message to be sent needs to be a part of the thread with the specified `parentMessageId`. +This can be achieved using the `setParentMessageId()` method provided by the object of the `TextMessage`, `MediaMessage`, and `CustomMessage` class. The id specified in the `setParentMessageId()` method maps the message sent to the particular thread. -This can be achieved using the `setParentMessageId()` method provided by the object of the `TextMessage`, `MediaMessage` and `CustomMessage` class. The id specified in the `setParentMessageId()` method maps the message sent to the particular thread. + +The `parentMessageId` is dynamic and corresponds to the actual `id` of the parent message you want to reply to. In the code examples below, we use placeholder values like `100` or `1`, but in practice, you'll use the actual message ID obtained from your message list or real-time listener. + -**Example to Send a Text Message in a thread in a user conversation.** +**Example to send a text message in a thread in a user conversation:** - + ```javascript let textMessage = new CometChat.TextMessage(UID, "Hello", CometChat.RECEIVER_TYPE.USER); -textMessage.setParentMessageId(100); +textMessage.setParentMessageId(100); // Replace with actual parent message ID CometChat.sendMessage(textMessage).then( message => { @@ -42,7 +74,7 @@ CometChat.sendMessage(textMessage).then( let receiverId = "UID", receiverType: string = CometChat.RECEIVER_TYPE.USER, textMessage: CometChat.TextMessage = new CometChat.TextMessage(receiverId, "Hello", receiverType), - messageId: number = 100; + messageId: number = 100; // Replace with actual parent message ID textMessage.setParentMessageId(messageId); @@ -61,16 +93,115 @@ CometChat.sendMessage(textMessage).then( The above snippet shows how a message with the text "Hello" can be sent in the thread with `parentMessageId` 100. -Similarly, using the `setparentMessageId()` method, Media and Custom Messages can be sent in threads too. +Similarly, using the `setParentMessageId()` method, Media and Custom Messages can be sent in threads too. + + +**On Success** — `sendMessage()` returns the sent threaded message with `parentMessageId`: +```json +{ + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "text": "Hello thread!", + "resource": "REACT_NATIVE-4_0_14-f8c2a36f-89cc-4a1a-8ef9-880f311c0d1d-1771838824248", + "entities": { + "sender": { + "entity": { + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771839550, + "tags": [] + }, + "entityType": "user" + }, + "receiver": { + "entity": { + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "status": "online", + "role": "default", + "lastActiveAt": 1771839549, + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "tags": [] + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "pending" + } + }, + "text": "Hello thread!", + "id": "25293", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771839550, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771839549, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771839799, + "updatedAt": 1771839799, + "parentMessageId": "25291", // This is the ID of the parent message - will vary based on your actual parent message + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } +} +``` + + + ### Receiving Real-Time Messages -The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/react-native/receive-messages). This can be achieved using the `MessageListener` class provided by the SDK. +The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/react-native/receive-messages) section. This can be achieved using the `MessageListener` class provided by the SDK. To add a MessageListener, you can use the `addMessageListener()` method of the SDK. The only thing that needs to be checked is if the received message belongs to the active thread. This can be done using the `parentMessageId` field of the message object. - + ```javascript var listenerID = "UNIQUE_LISTENER_ID"; var activeThreadId = 100; @@ -130,17 +261,21 @@ CometChat.addMessageListener( -### Fetch all the messages for any particular thread. + +**Remember to remove your listener on unmount.** Always call `CometChat.removeMessageListener("UNIQUE_LISTENER_ID")` when the component unmounts (e.g., in a `useEffect` cleanup or `componentWillUnmount`) to avoid memory leaks and duplicate event handling. + + +### Fetch All Messages for a Thread -You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. In order to get an object of the `MessagesRequest` class, you need to use the `MessagesRequestBuilder` class. and use the `setParentMessageId()` method of the `MessagesRequestBuilder` to inform the SDK that you only need the messages belonging to the thread with the specified parentMessageId. +You can fetch all the messages belonging to a particular thread by using the `MessagesRequest` class. To get an object of the `MessagesRequest` class, use the `MessagesRequestBuilder` class and call the `setParentMessageId()` method to inform the SDK that you only need the messages belonging to the thread with the specified `parentMessageId`. -Once you have the object of the `MessagesRequest` class, you need to call the `fetchPrevious()` method to get the latest messages in the thread. In one integration, a maximum of 100 messages can be fetched. If you wish to fetch the next set of messages, you need to call the `fetchPrevious()` method again on the same object. +Once you have the object of the `MessagesRequest` class, call the `fetchPrevious()` method to get the latest messages in the thread. In one call, a maximum of 100 messages can be fetched. To fetch the next set of messages, call the `fetchPrevious()` method again on the same object. - + ```javascript let limit = 30; -let parentMessageId = 1; +let parentMessageId = 1; // Replace with actual parent message ID let messagesRequest = new CometChat.MessagesRequestBuilder() .setLimit(limit) .setParentMessageId(parentMessageId) @@ -160,7 +295,7 @@ messagesRequest.fetchPrevious().then( ```typescript let limit: number = 30, - parentMessageId: number = 1, + parentMessageId: number = 1, // Replace with actual parent message ID messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder() .setLimit(limit) .setParentMessageId(parentMessageId) @@ -179,12 +314,301 @@ messagesRequest.fetchPrevious().then( + +**On Success** — `fetchPrevious()` returns an array of messages belonging to the thread: +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771839549, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771839550, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-f8c2a36f-89cc-4a1a-8ef9-880f311c0d1d-1771838824248", + "text": "Hello thread!" + }, + "text": "Hello thread!", + "id": "25293", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771839550, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771839549, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771839799, + "updatedAt": 1771839799, + "parentMessageId": "25291", // Dynamic - matches the parent message's ID you're fetching replies for + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more thread messages up to the specified limit +] +``` + + ## Avoid Threaded Messages in User/Group Conversations -While fetching messages for normal user/group conversations using the `MessagesRequest`, the threaded messages by default will be a part of the list of messages received. In order to exclude the threaded messages from the list of user/group messages, you need to use the `hideReplies()` method of the `MessagesRequestBuilder` class. This method takes a boolean argument which when set to true excludes the messages belonging to threads from the list of messages. +While fetching messages for normal user/group conversations using the `MessagesRequest`, threaded messages will be included in the list by default. To exclude threaded messages from the list of user/group messages, use the `hideReplies()` method of the `MessagesRequestBuilder` class. This method takes a boolean argument which, when set to `true`, excludes messages belonging to threads from the list of messages. + + +**Without `hideReplies(true)`** — `fetchPrevious()` returns all messages including thread replies (note the second message has `parentMessageId`): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-6", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771829859, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-b495efdd-5a54-4a47-a8ad-237bf8dff679-1771829544163", + "text": "Hello" + }, + "text": "Hello", + "id": "25291", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771829859, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771831336, + "deliveredAt": 1771832977, + "readAt": 1771832977, + "updatedAt": 1771832977, + "replyCount": 1, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-7", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771839549, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771839550, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "moderation": { + "status": "approved" + }, + "resource": "REACT_NATIVE-4_0_14-f8c2a36f-89cc-4a1a-8ef9-880f311c0d1d-1771838824248", + "text": "Hello thread!" + }, + "text": "Hello thread!", + "id": "25293", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771839550, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771839549, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771839799, + "updatedAt": 1771839799, + "parentMessageId": "25291", // Dynamic - this links the reply to its parent message (id: 25291) + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + } +] +``` + - + ```javascript let UID = "UID"; let limit = 30; @@ -205,7 +629,7 @@ messagesRequest.fetchPrevious().then( - + ```javascript let GUID = "GUID"; let limit = 30; @@ -226,7 +650,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let UID: string = "UID", limit: number = 30, @@ -247,7 +671,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -270,4 +694,140 @@ messagesRequest.fetchPrevious().then( -The above snippet will return messages between the logged in user and `cometchat-uid-1` excluding all the threaded messages belonging to the same conversation. + +**On Success** — `fetchPrevious()` returns messages excluding thread replies (note: parent messages with `replyCount` are included, but their replies are not): +```json +[ + { + "reactions": [], + "mentionedUsers": [], + "mentionedMe": false, + "receiverId": "cometchat-uid-6", + "type": "text", + "receiverType": "user", + "category": "message", + "data": { + "entities": { + "receiver": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "lastActiveAt": 1771829859, + "name": "Ronald Jerry", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-6" + }, + "entityType": "user" + }, + "sender": { + "entity": { + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "name": "Henry Marino", + "role": "default", + "status": "online", + "tags": [], + "uid": "cometchat-uid-7" + }, + "entityType": "user" + } + }, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + }, + "resource": "REACT_NATIVE-4_0_14-b495efdd-5a54-4a47-a8ad-237bf8dff679-1771829544163", + "text": "Hello" + }, + "text": "Hello", + "id": "25291", + "conversationId": "cometchat-uid-6_user_cometchat-uid-7", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-7", + "name": "Henry Marino", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp", + "lastActiveAt": 1771829868, + "role": "default", + "status": "online", + "tags": [] + }, + "receiver": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "lastActiveAt": 1771829859, + "role": "default", + "status": "online", + "tags": [] + }, + "sentAt": 1771831336, + "deliveredAt": 1771832977, + "readAt": 1771832977, + "updatedAt": 1771832977, + "replyCount": 1, + "metadata": { + "@injected": { + "extensions": { + "link-preview": { + "links": [] + } + } + } + } + }, + // ... more messages up to the specified limit (thread replies excluded) +] +``` + + +The above snippet will return messages between the logged-in user and `cometchat-uid-1` excluding all the threaded messages belonging to the same conversation. + +## Best Practices and Troubleshooting + + + + Every message object has a `parentMessageId` field. If this field is set (non-zero), the message is part of a thread. Use `message.getParentMessageId()` to retrieve the parent message ID and match it against the active thread. + + + + By default, `MessagesRequest` includes threaded messages. Use the `hideReplies(true)` method on `MessagesRequestBuilder` when fetching messages for the main conversation to exclude thread replies. + + + + You can fetch a maximum of 100 messages per `fetchPrevious()` call. Use the `setLimit()` method on `MessagesRequestBuilder` to control the number of messages returned. To load more messages, call `fetchPrevious()` again on the same `MessagesRequest` object. + + + + Yes. The `setParentMessageId()` method is available on `TextMessage`, `MediaMessage`, and `CustomMessage` objects. Set the parent message ID before calling `CometChat.sendMessage()` to send any message type within a thread. + + + +## Next Steps + + + + Learn how to send text, media, and custom messages to users and groups. + + + Set up real-time message listeners and fetch message history. + + + Filter messages by type, category, tags, timestamps, and more. + + + Understand message categories, types, and the message hierarchy. + + \ No newline at end of file diff --git a/sdk/react-native/transfer-group-ownership.mdx b/sdk/react-native/transfer-group-ownership.mdx index 1de52a892..0b2595cbc 100644 --- a/sdk/react-native/transfer-group-ownership.mdx +++ b/sdk/react-native/transfer-group-ownership.mdx @@ -1,8 +1,19 @@ --- title: "Transfer Group Ownership" +description: "Learn how to transfer group ownership to another member using the CometChat React Native SDK." --- + +**Quick Reference** +```javascript +// Transfer group ownership +CometChat.transferGroupOwnership("GUID", "UID"); +``` + + +Available via: [SDK](/sdk/react-native/transfer-group-ownership) | [REST API](/rest-api/groups/update) + *In other words, as a logged-in user, how do I transfer the ownership of any group if I am the owner of the group?* @@ -11,7 +22,7 @@ In order to transfer the ownership of any group, the first condition is that you This will be helpful as the owner is not allowed to leave the group. In case, you as the owner would like to leave the group, you will have to use this method and transfer your ownership first to any other member of the group and only then you will be allowed to leave the group. - + ```javascript let GUID = "GUID"; let UID = "UID"; @@ -42,3 +53,36 @@ CometChat.transferGroupOwnership(GUID, UID).then( + + + +- Always confirm with the user before transferring ownership — this action cannot be undone without the new owner's cooperation +- Transfer ownership before leaving a group, as the owner is not allowed to leave without doing so +- After transferring ownership, the previous owner's scope is automatically changed — update your UI accordingly +- Consider showing a list of current group members to let the owner pick the new owner easily + + + +- **ERR_NOT_A_MEMBER**: The logged-in user is not a member of the group. Ensure the user has joined the group first. +- **ERR_INSUFFICIENT_PERMISSIONS**: Only the group owner can transfer ownership. Verify the logged-in user is the owner, not just an admin. +- **Cannot leave group**: You must transfer ownership first before leaving. Use `transferGroupOwnership()` then `leaveGroup()`. +- **Target user not found**: Ensure the UID belongs to an existing member of the group. You cannot transfer ownership to a non-member. + + + +## Next Steps + + + +Leave a group after transferring ownership + + +Promote or demote group members + + +Remove or restrict members from a group + + +Permanently delete a group + + diff --git a/sdk/react-native/transient-messages.mdx b/sdk/react-native/transient-messages.mdx index 1fea8e192..299093294 100644 --- a/sdk/react-native/transient-messages.mdx +++ b/sdk/react-native/transient-messages.mdx @@ -1,7 +1,22 @@ --- title: "Transient Messages" +description: "Send and receive real-time transient messages that are not stored or tracked using the CometChat React Native SDK." --- + +**Quick Reference** — Send a transient message: + +```javascript +let data = { "LIVE_REACTION": "heart" }; +let transientMessage = new CometChat.TransientMessage("RECEIVER_ID", CometChat.RECEIVER_TYPE.USER, data); +CometChat.sendTransientMessage(transientMessage); +``` + + + + +**Available via:** [SDK](/sdk/react-native/transient-messages) + Transient messages are messages that are sent in real-time only and are not saved or tracked anywhere. The receiver of the message will only receive the message if he is online and these messages cannot be retrieved later. @@ -11,7 +26,7 @@ Transient messages are messages that are sent in real-time only and are not save You can use the `sendTransientMessage()` method to send a transient message to a user or in a group. The receiver will receive this information in the `onTransientMessageReceived()` method of the `MessageListener` class. In order to send the transient message, you need to use the `TransientMessage` class. - + ```javascript let receiverId = "UID"; let receiverType = CometChat.RECEIVER_TYPE.USER; @@ -23,7 +38,7 @@ CometChat.sendTransientMessage(transientMessage); - + ```javascript let receiverId = "GUID"; let receiverType = CometChat.RECEIVER_TYPE.GROUP; @@ -35,7 +50,7 @@ CometChat.sendTransientMessage(transientMessage); - + ```typescript let receiverId: string = "UID"; let receiverType: string = CometChat.RECEIVER_TYPE.USER; @@ -47,7 +62,7 @@ CometChat.sendTransientMessage(transientMessage); - + ```typescript let receiverId: string = "GUID"; let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; @@ -61,6 +76,19 @@ CometChat.sendTransientMessage(transientMessage); + +**On Success** — `sendTransientMessage()` does not return a value, but the transient message object sent looks like: +```json +{ + "receiverId": "cometchat-uid-7", + "receiverType": "user", + "data": { + "LIVE_REACTION": "heart" + } +} +``` + + ## Real-time Transient Messages *In other words, as a recipient, how do I know when someone sends a transient message?* @@ -68,7 +96,7 @@ CometChat.sendTransientMessage(transientMessage); You will receive the transient message in the `onTransientMessageReceived()` method of the registered `MessageListener` class. - + ```javascript let listenerId = "UNIQUE_LITENER_ID"; @@ -102,6 +130,34 @@ CometChat.addMessageListener( + +**On Event** — `onTransientMessageReceived` returns the transient message object with sender info: +```json +{ + "receiverId": "cometchat-uid-7", + "receiverType": "user", + "data": { + "LIVE_REACTION": "heart" + }, + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "role": "default", + "status": "online", + "tags": [] + } +} +``` + + + +**Listener Cleanup** — Always remove your message listeners when the component unmounts to prevent memory leaks and unexpected behavior. Use `CometChat.removeMessageListener("UNIQUE_LITENER_ID")` in your cleanup logic (e.g., inside a `useEffect` return function or `componentWillUnmount`). + + The `TransientMessage` class consists of the below parameters: | Parameter | Information | @@ -110,3 +166,37 @@ The `TransientMessage` class consists of the below parameters: | **receiverId** | Unique Id of the receiver. This can be the Id of the group or the user the transient message is sent to. | | **receiverType** | The type of the receiver - `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | | **data** | A JSONObject to provide data. | + + + +- **Use transient messages for ephemeral interactions only** — Since transient messages are not stored, they are ideal for features like live reactions, presence pings, or real-time indicators that don't need to persist. +- **Keep the data payload small** — Transient messages are designed for lightweight, real-time signals. Avoid sending large JSON objects in the `data` field. +- **Use unique listener IDs** — Each screen or component that registers a `MessageListener` should use a distinct `listenerId` to avoid conflicts with other listeners. +- **Confirm the receiver is online** — Transient messages are only delivered to online users. If guaranteed delivery is required, use a regular [message](/sdk/react-native/send-message) instead. +- **Pair with typing indicators for richer UX** — Combine transient messages with [typing indicators](/sdk/react-native/typing-indicators) to build expressive, real-time chat experiences. + + +- **Recipient not receiving transient messages** — Verify that the recipient is online and has registered a `MessageListener` with the `onTransientMessageReceived` callback before the sender dispatches the message. +- **Listener not firing** — Confirm that the `listenerId` used in `addMessageListener` is unique and that the listener has not been removed prematurely. +- **Messages not arriving in groups** — Make sure you are using `CometChat.RECEIVER_TYPE.GROUP` with the correct group ID (`GUID`), not a user ID. +- **Cannot retrieve transient messages later** — This is expected behavior. Transient messages are never stored. If you need message persistence, use [send a message](/sdk/react-native/send-message) instead. +- **Data field appears empty on the receiver side** — Ensure you are passing a valid JSON object to the `data` parameter when constructing the `TransientMessage` instance. + + + +## Next Steps + + + + Send and receive real-time typing indicators in conversations. + + + Send text, media, and custom messages to users and groups. + + + Set up real-time and fetch-based message receiving. + + + Explore the full messaging feature set available in the SDK. + + diff --git a/sdk/react-native/typing-indicators.mdx b/sdk/react-native/typing-indicators.mdx index 4a025a9da..8389847d3 100644 --- a/sdk/react-native/typing-indicators.mdx +++ b/sdk/react-native/typing-indicators.mdx @@ -1,8 +1,29 @@ --- title: "Typing Indicators" +description: "Learn how to send and receive real-time typing indicators in one-on-one and group conversations using the CometChat React Native SDK." --- + +**Quick Reference** — Send and listen for typing indicators: +```javascript +// Start typing +let typing = new CometChat.TypingIndicator("RECEIVER_ID", CometChat.RECEIVER_TYPE.USER); +CometChat.startTyping(typing); + +// Stop typing +CometChat.endTyping(typing); + +// Listen for typing events +CometChat.addMessageListener("listenerId", new CometChat.MessageListener({ + onTypingStarted: (indicator) => { /* sender is typing */ }, + onTypingEnded: (indicator) => { /* sender stopped typing */ }, +})); +``` + + +**Available via:** [SDK](/sdk/react-native/typing-indicators) | [UI Kits](/ui-kit/react-native/core-features#typing-indicator) + ## Send a Typing Indicator @@ -10,10 +31,10 @@ title: "Typing Indicators" ### Start Typing -You can use the `startTyping()` method to inform the receiver that the logged in user has started typing. The receiver will receive this information in the `onTypingStarted()` method of the `MessageListener` class. In order to send the typing indicator, you need to use the `TypingIndicator` class. +You can use the `startTyping()` method to inform the receiver that the logged-in user has started typing. The receiver will receive this information in the `onTypingStarted()` method of the `MessageListener` class. To send the typing indicator, you need to use the `TypingIndicator` class. - + ```javascript let receiverId = "UID"; let receiverType = CometChat.RECEIVER_TYPE.USER; @@ -24,7 +45,7 @@ CometChat.startTyping(typingNotification); - + ```javascript let receiverId = "GUID"; let receiverType = CometChat.RECEIVER_TYPE.GROUP; @@ -35,7 +56,7 @@ CometChat.startTyping(typingNotification); - + ```typescript let receiverId: string = "UID"; let receiverType: string = CometChat.RECEIVER_TYPE.USER; @@ -46,7 +67,7 @@ CometChat.startTyping(typingNotification); - + ```typescript let receiverId: string = "GUID"; let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; @@ -59,12 +80,22 @@ CometChat.startTyping(typingNotification); + +**startTyping called** — the typing indicator object sent to the receiver: +```json +{ + "receiverId": "cometchat-uid-6", + "receiverType": "user" +} +``` + + ### Stop Typing -You can use the `endTyping()` method to inform the receiver that the logged in user has stopped typing. The receiver will receive this information in the `onTypingEnded()` method of the `MessageListener` class. In order to send the typing indicator, you need to use the `TypingIndicator` class. +You can use the `endTyping()` method to inform the receiver that the logged-in user has stopped typing. The receiver will receive this information in the `onTypingEnded()` method of the `MessageListener` class. To send the typing indicator, you need to use the `TypingIndicator` class. - + ```javascript let receiverId = "UID"; let receiverType = CometChat.RECEIVER_TYPE.USER; @@ -75,7 +106,7 @@ CometChat.endTyping(typingNotification); - + ```javascript let receiverId = "GUID"; let receiverType = CometChat.RECEIVER_TYPE.GROUP; @@ -86,7 +117,7 @@ CometChat.endTyping(typingNotification); - + ```typescript let receiverId: string = "UID"; let receiverType: string = CometChat.RECEIVER_TYPE.USER; @@ -97,7 +128,7 @@ CometChat.endTyping(typingNotification); - + ```typescript let receiverId: string = "GUID"; let receiverType: string = CometChat.RECEIVER_TYPE.GROUP; @@ -110,6 +141,16 @@ CometChat.endTyping(typingNotification); + +**endTyping called** — the typing indicator object sent to the receiver: +```json +{ + "receiverId": "cometchat-uid-6", + "receiverType": "user" +} +``` + + Custom Data @@ -124,7 +165,7 @@ You can use the `metadata` field of the `TypingIndicator` class to pass addition You will receive the typing indicators in the `onTypingStarted()` and the `onTypingEnded()` method of the registered `MessageListener` class. - + ```javascript let listenerId = "UNIQUE_LITENER_ID"; @@ -164,11 +205,87 @@ CometChat.addMessageListener( + +**onTypingStarted** — received when a user starts typing: +```json +{ + "receiverId": "cometchat-uid-7", + "receiverType": "user", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "role": "default", + "status": "online", + "tags": [] + } +} +``` + +**onTypingEnded** — received when a user stops typing: +```json +{ + "receiverId": "cometchat-uid-7", + "receiverType": "user", + "sender": { + "hasBlockedMe": false, + "blockedByMe": false, + "deactivatedAt": 0, + "uid": "cometchat-uid-6", + "name": "Ronald Jerry", + "avatar": "https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp", + "role": "default", + "status": "online", + "tags": [] + } +} +``` + + + +**Listener Cleanup** — Always remove your message listeners when the component unmounts to prevent memory leaks and unexpected behavior. Use `CometChat.removeMessageListener("UNIQUE_LITENER_ID")` in your cleanup logic (e.g., inside a `useEffect` return function or `componentWillUnmount`). + + The `TypingIndicator` class consists of the below parameters: | Parameter | Information | | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **sender** | An object of the `User` class holding all the information. related to the sender of the typing indicator. | +| **sender** | An object of the `User` class holding all the information related to the sender of the typing indicator. | | **receiverId** | Unique Id of the receiver. This can be the Id of the group or the user the typing indicator is sent to. | | **receiverType** | This parameter indicates if the typing indicator is to be sent to a user or a group. The possible values are: 1. `CometChat.RECEIVER_TYPE.USER` 2. `CometChat.RECEIVER_TYPE.GROUP` | -| **metadata** | A JSONObject to provider additional data. | +| **metadata** | A JSONObject to provide additional data. | + + + +- **Debounce start typing calls** — Avoid calling `startTyping()` on every keystroke. Instead, debounce the call so it fires once when the user begins typing and doesn't repeat until after a short pause. +- **Call endTyping() explicitly** — Always call `endTyping()` when the user clears the input field, sends a message, or navigates away from the chat screen. +- **Use unique listener IDs** — Each screen or component that registers a `MessageListener` should use a distinct `listenerId` to avoid conflicts. +- **Handle metadata sparingly** — Only attach `metadata` to typing indicators when you have a concrete use case (e.g., indicating which thread the user is typing in). + + +- **Typing indicator not appearing for the recipient** — Verify that the recipient has registered a `MessageListener` with `onTypingStarted` and `onTypingEnded` callbacks before the sender starts typing. +- **Typing indicator stuck in "typing" state** — Ensure `endTyping()` is called when the user stops typing or sends a message. CometChat automatically times out typing indicators after a short period, but explicitly ending them provides a better user experience. +- **Listener not firing** — Confirm that the `listenerId` used in `addMessageListener` is unique and that the listener has not been removed prematurely. +- **Indicators not working in groups** — Make sure you are using `CometChat.RECEIVER_TYPE.GROUP` with the correct group ID (`GUID`), not a user ID. + + + +## Next Steps + + + + Confirm when messages are delivered and read by recipients. + + + Learn how to send text, media, and custom messages. + + + Set up real-time and fetch-based message receiving. + + + Explore the full messaging feature set available in the SDK. + + diff --git a/sdk/react-native/update-group.mdx b/sdk/react-native/update-group.mdx index e8e635926..36ce7b99e 100644 --- a/sdk/react-native/update-group.mdx +++ b/sdk/react-native/update-group.mdx @@ -1,8 +1,20 @@ --- title: "Update A Group" +description: "Update group details such as name, icon, description, and metadata using the CometChat React Native SDK." --- + +**Quick Reference** - Update a group: +```javascript +const group = new CometChat.Group("GUID", "Updated Name", CometChat.GROUP_TYPE.PUBLIC); +await CometChat.updateGroup(group); +``` + + + +**Available via:** [SDK](/sdk/react-native/update-group) | [REST API](/rest-api/groups/update) + ## Update Group @@ -11,7 +23,7 @@ title: "Update A Group" You can update the existing details of the group using the `updateGroup()` method. - + ```javascript var GUID = "GUID"; var groupName = "Hello Group"; @@ -59,3 +71,44 @@ This method takes an instance of the `Group` class as a parameter which should c After a successful update of the group, you will receive an instance of `Group` class containing update information of the group. For more information on the `Group` class, please check [here](/sdk/react-native/create-group#group-class) + +## Best Practices + + + + The `Group` object passed to `updateGroup()` must have the correct GUID set. Only the fields you set on the object will be updated — unset fields remain unchanged. + + + The `updateGroup()` method requires the logged-in user to be the owner or an admin of the group. Participants and moderators cannot update group details. + + + +## Troubleshooting + + + + Verify the logged-in user is the owner or an admin of the group. Use `getGroup()` to check the user's scope in the group. + + + The `type` field of a group is not editable after creation. To change a group's type, you would need to create a new group with the desired type. + + + +--- + +## Next Steps + + + + Fetch group lists, search groups, and get group details + + + Manage members, roles, and permissions within groups + + + Delete groups and handle related cleanup + + + Create public, private, or password-protected groups + + \ No newline at end of file diff --git a/sdk/react-native/upgrading-from-v3.mdx b/sdk/react-native/upgrading-from-v3.mdx index a2186f43f..1d9222872 100644 --- a/sdk/react-native/upgrading-from-v3.mdx +++ b/sdk/react-native/upgrading-from-v3.mdx @@ -1,8 +1,23 @@ --- title: "Upgrading From V3" +description: "Learn how to upgrade your React Native app from CometChat SDK v3 to v4, including dependency changes and updated import statements." --- + +**Quick Reference** +```bash +# Install v4 Chat SDK +npm i @cometchat/chat-sdk-react-native +# Install v4 Calls SDK +npm i @cometchat/calls-sdk-react-native +``` +```javascript +// Updated imports +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { CometChatCalls } from '@cometchat/calls-sdk-react-native'; +``` + Upgrading from v3.x to v4 is fairly simple. Below are the major changes that are released as a part of CometChat v4: @@ -61,3 +76,30 @@ import {CometChatCalls} from '@cometchat/calls-sdk-react-native'; + + + +- Update both the Chat SDK and Calls SDK together to avoid version incompatibilities +- After updating dependencies, do a clean build (`npx react-native start --reset-cache`) to clear any cached modules +- Search your entire project for old import paths (`@cometchat-pro/react-native-chat`) and replace them with the new v4 paths +- Test all listeners and callbacks after upgrading — some callback signatures may have changed between v3 and v4 + + + +- **Module not found errors**: Ensure you've removed the old v3 packages (`@cometchat-pro/react-native-chat`) and installed the new v4 packages. +- **Duplicate module errors**: Run `npm dedupe` or delete `node_modules` and reinstall to resolve conflicting versions. +- **iOS build fails after upgrade**: Run `pod install --repo-update` in the `ios/` directory to update native dependencies. +- **Android build fails**: Clean the build with `./gradlew clean` in the `android/` directory and rebuild. + + + +## Next Steps + + + +Complete the v4 SDK setup + + +Set up user authentication with v4 + + diff --git a/sdk/react-native/user-management.mdx b/sdk/react-native/user-management.mdx index 61312c62c..e6a8b0afd 100644 --- a/sdk/react-native/user-management.mdx +++ b/sdk/react-native/user-management.mdx @@ -1,8 +1,27 @@ --- title: "User Management" +description: "Create, update, and delete users in CometChat using the React Native SDK — including logged-in user updates and the User class reference." --- + +**Quick Reference** - Create and update users: +```javascript +// Create a user +const user = new CometChat.User("user1"); +user.setName("Kevin"); +await CometChat.createUser(user, "AUTH_KEY"); + +// Update logged-in user +const me = new CometChat.User("user1"); +me.setName("Kevin Fernandez"); +await CometChat.updateCurrentUserDetails(me); +``` + + + +**Available via:** [SDK](/sdk/react-native/user-management) | [REST API](/rest-api/users/create) + When a user logs into your app, you need to programmatically login the user into CometChat. But before you log in the user to CometChat, you need to create the user. @@ -20,10 +39,14 @@ Summing up- ## Creating a user -Ideally, user creation should take place at your backend. You can refer to our Rest API to learn more about [creating a user](https://api-explorer.cometchat.com/reference/creates-user) and use the appropriate code sample based on your backend language. +Ideally, user creation should take place at your backend. You can refer to our Rest API to learn more about [creating a user](https://www.cometchat.com/docs/rest-api/users/create) and use the appropriate code sample based on your backend language. However, if you wish to create users on the fly, you can use the `createUser()` method. This method takes a `User` object and the `Auth Key` as input parameters and returns the created `User` object if the request is successful. + +The `Auth Key` is intended for development and testing only. In production, create users from your backend using the [REST API](/rest-api/create-user) with your API Key instead. + + ```javascript @@ -69,15 +92,49 @@ CometChat.createUser(user, authKey).then( + +**On Success** — `createUser()` returns the created `User` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"test_user_1772166127823"` | +| `name` | string | Display name of the user | `"Test User"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `createdAt` | number | Unix timestamp when user was created | `1772166128` | + +When creating a user with all optional fields set: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"test_full_1772166127993"` | +| `name` | string | Display name of the user | `"Full Test User"` | +| `avatar` | string | URL to user's avatar image | `"https://example.com/avatar.png"` | +| `link` | string | URL to user's profile page | `"https://example.com/profile"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `statusMessage` | string | Custom status message | `"Hello World"` | +| `metadata` | object | Custom metadata attached to the user | `{"custom": "data"}` | +| `tags` | array | Tags associated with the user | `["tag1", "tag2"]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `createdAt` | number | Unix timestamp when user was created | `1772166129` | + + + -UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. +UID can be alphanumeric with underscore and hyphen. Spaces, punctuation and other special characters are not allowed. CometChat automatically converts any uppercase characters in the UID to lowercase. ## Updating a user -Updating a user similar to creating a user should ideally be achieved at your backend using the Restful APIs. For more information, you can check the [update a user](https://api-explorer.cometchat.com/reference/update-user) section. However, this can be achieved on the fly as well as using the `updateUser()` method. This method takes a `User` object and the `Auth Key` as inputs and returns the updated `User` object on the successful execution of the request. +Updating a user similar to creating a user should ideally be achieved at your backend using the Restful APIs. For more information, you can check the [update a user](https://www.cometchat.com/docs/rest-api/users/update) section. However, this can be achieved on the fly as well as using the `updateUser()` method. This method takes a `User` object and the `Auth Key` as inputs and returns the updated `User` object on the successful execution of the request. @@ -124,6 +181,40 @@ CometChat.updateUser(user, authKey).then( + +**On Success** — `updateUser()` returns the updated `User` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"test_user_1772167015122"` | +| `name` | string | Display name of the user | `"Updated Test User"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `createdAt` | number | Unix timestamp when user was created | `1772167016` | + +When updating a user with all optional fields: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"test_full_1772167015291"` | +| `name` | string | Display name of the user | `"Updated Full User"` | +| `avatar` | string | URL to user's avatar image | `"https://example.com/new-avatar.png"` | +| `link` | string | URL to user's profile page | `"https://example.com/new-profile"` | +| `role` | string | User's role | `"admin"` | +| `status` | string | User's online status | `"offline"` | +| `statusMessage` | string | Custom status message | `"Updated status"` | +| `metadata` | object | Custom metadata attached to the user | `{"updated": true}` | +| `tags` | array | Tags associated with the user | `["updated-tag"]` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `createdAt` | number | Unix timestamp when user was created | `1772167016` | + + + Please make sure the `User` object provided to the `updateUser()` method has the `UID` of the user to be updated set. ## Updating logged-in user @@ -173,11 +264,34 @@ CometChat.updateCurrentUserDetails(user).then( + +**On Success** — `updateCurrentUserDetails()` returns the updated `User` object with additional session data: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | +| `authToken` | string | Authentication token for the user | `"cometchat-uid-7_177199269018c2c2995f0b69b3844abc9fdb9843"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `statusMessage` | string | Custom status message | `"Testing CometChat SDK"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772163866` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | +| `tags` | array | Tags associated with the user | `["vip"]` | +| `wsChannel` | object | WebSocket channel information | `{"identity": "[2748663902141719]cometchat-uid-7"}` | +| `settings` | object | App settings and feature flags (large object with trial info, extensions, parameters) | See CometChat Dashboard | +| `jwt` | string | JSON Web Token for API authentication | JWT string | + + + By using the `updateCurrentUserDetails()` method one can only update the logged-in user irrespective of the UID passed. Also, it is not possible to update the role of a logged-in user. ## Deleting a user -Deleting a user can only be achieved via the Restful APIs. For more information please check the [delete a user](https://api-explorer.cometchat.com/reference/delete-user) section. +Deleting a user can only be achieved via the Restful APIs. For more information please check the [delete a user](https://www.cometchat.com/docs/rest-api/users/delete) section. ## User Class @@ -195,3 +309,50 @@ Deleting a user can only be achieved via the Restful APIs. For more information | hasBlockedMe | No | A boolean that determines if the user has blocked the logged in user | | blockedByMe | No | A boolean that determines if the logged in user has blocked the user | | tags | Yes | A list of tags to identify specific users | + +## Best Practices + + + + Use the REST API with your API Key to create users server-side. The `createUser()` SDK method requires the Auth Key, which should not be exposed in production client apps. + + + Use the same user identifier from your backend as the CometChat UID. This simplifies mapping between your user system and CometChat. + + + When the logged-in user updates their own profile, use `updateCurrentUserDetails()` which doesn't require an Auth Key. Reserve `updateUser()` for admin-level operations from your backend. + + + +## Troubleshooting + + + + Each UID must be unique across your CometChat app. If the user already exists, use `updateUser()` instead, or skip creation and proceed to login. + + + Role updates are not allowed via `updateCurrentUserDetails()`. Use the REST API or `updateUser()` with Auth Key to change a user's role. + + + UIDs can only contain alphanumeric characters, underscores, and hyphens. Spaces, punctuation, and other special characters are not allowed. + + + +--- + +## Next Steps + + + + Fetch user lists, search users, and get user details + + + Block and unblock users, retrieve blocked user lists + + + Log users into CometChat after creation + + + Track online/offline status of users in real time + + \ No newline at end of file diff --git a/sdk/react-native/user-presence.mdx b/sdk/react-native/user-presence.mdx index 983f9b7d1..f03f1fd85 100644 --- a/sdk/react-native/user-presence.mdx +++ b/sdk/react-native/user-presence.mdx @@ -1,8 +1,25 @@ --- title: "User Presence" +description: "Track real-time online/offline status of users in your React Native app using CometChat SDK presence subscriptions and user listeners." --- + +**Quick Reference** - Listen for user presence changes: +```javascript +CometChat.addUserListener("LISTENER_ID", new CometChat.UserListener({ + onUserOnline: (user) => console.log("Online:", user), + onUserOffline: (user) => console.log("Offline:", user), +})); + +// Cleanup +CometChat.removeUserListener("LISTENER_ID"); +``` + + + +**Available via:** [SDK](/sdk/react-native/user-presence) | [UI Kits](/ui-kit/react-native/users) + User Presence helps us understand if a user is available to chat or not. @@ -25,7 +42,7 @@ If none of the above methods are used, no presence will be sent to the logged-in You need to register the `UserListener` using the `addUserListener()` method where ever you wish to receive these events in. - + ```javascript let listenerID = "UNIQUE_LISTENER_ID"; @@ -65,18 +82,56 @@ CometChat.addUserListener( + +**On Event** — `onUserOnline` returns a `User` object when a user comes online: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772174142305` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | + + + + +**On Event** — `onUserOffline` returns a `User` object when a user goes offline: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | +| `name` | string | Display name of the user | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar image | `"https://artriva.com/media/k2/galleries/20/d.jpg"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772174136215` | +| `hasBlockedMe` | boolean | Whether this user has blocked the current user | `false` | +| `blockedByMe` | boolean | Whether the current user has blocked this user | `false` | +| `deactivatedAt` | number | Timestamp when user was deactivated (0 if active) | `0` | + + + | Parameter | Description | | ------------ | --------------------------------------------- | | `listenerID` | An ID that uniquely identifies that listener. | You will receive an object of the `User` class in the listener methods. -We recommend you remove the listener when not in use. + +Presence events are triggered for other users, not for yourself. For example, if User 1 is logged in and User 2 comes online, User 1 receives `onUserOnline` for User 2. Neither User 1 nor User 2 receive presence events for their own status changes — only for others. + -We suggest removing listener in componentWillUnmount() method when not in use. + +Always remove user listeners when the component unmounts using `CometChat.removeUserListener(listenerID)`. Failing to remove listeners can cause memory leaks and duplicate event handling. + - + ```javascript let listenerID = "UNIQUE_LISTENER_ID"; CometChat.removeUserListener(listenerID); @@ -106,3 +161,50 @@ When you fetch the list of users, in the [User](/sdk/react-native/user-managemen * offline - This indicates that the user is currently offline and is not available to chat. 2. `lastActiveAt` - in case the user is offline, this field holds the timestamp of the time when the user was last online. This can be used to display the Last seen of the user if need be. + +## Best Practices + + + + Use `subscribePresenceForAllUsers()` only if your app needs to track all users. For most apps, `subscribePresenceForFriends()` or `subscribePresenceForRoles()` is more efficient and reduces unnecessary network traffic. + + + Presence subscription is configured in `AppSettings` during SDK initialization. You cannot change the subscription type without re-initializing the SDK. Plan your subscription strategy before calling `init()`. + + + When a user is offline, use the `lastActiveAt` timestamp to show "Last seen X minutes ago" in your UI. This gives users context about when the person was last available. + + + +## Troubleshooting + + + + Verify that you configured a presence subscription method (`subscribePresenceForAllUsers`, `subscribePresenceForRoles`, or `subscribePresenceForFriends`) in your `AppSettings` during `init()`. Without this, no presence events are delivered. + + + Offline events are triggered when the SDK detects the user has disconnected. This may have a short delay depending on network conditions. The event will fire once the server confirms the user is offline. + + + If using `subscribePresenceForRoles()`, ensure the target users have the specified roles assigned. If using `subscribePresenceForFriends()`, confirm the users are in each other's friends list. + + + +--- + +## Next Steps + + + + Fetch user lists with online/offline status + + + Create, update, and delete users in CometChat + + + Block and unblock users, retrieve blocked user lists + + + Configure AppSettings including presence subscriptions + + \ No newline at end of file diff --git a/sdk/react-native/users-overview.mdx b/sdk/react-native/users-overview.mdx index b00b6b07a..8c8c40333 100644 --- a/sdk/react-native/users-overview.mdx +++ b/sdk/react-native/users-overview.mdx @@ -1,10 +1,30 @@ --- title: "Users" sidebarTitle: "Overview" +description: "Overview of user functionality in CometChat React Native SDK — create, retrieve, and manage users in your app." --- - +## Overview The primary aim for our Users functionality is to allow you to quickly add users to CometChat. You can begin with [user management](/sdk/react-native/user-management) to sync your users to CometChat. Once that is done, you can [retrieve users](/sdk/react-native/retrieve-users) and display them in your app. + +--- + +## Next Steps + + + + Create, update, and delete users in CometChat + + + Fetch user lists, search users, and get user details + + + Block and unblock users, retrieve blocked user lists + + + Track online/offline status of users in real time + + \ No newline at end of file diff --git a/sdk/react-native/video-view-customisation.mdx b/sdk/react-native/video-view-customisation.mdx index b8e9cb2c0..b38e36d98 100644 --- a/sdk/react-native/video-view-customisation.mdx +++ b/sdk/react-native/video-view-customisation.mdx @@ -1,20 +1,35 @@ --- title: "Video View Customisation" +description: "Customize the main video container in CometChat React Native calls, including aspect ratio, full-screen button, name labels, zoom, and user list button positioning." --- + +**Quick Reference** - Customize the main video container: +```javascript +let videoSettings = new CometChat.MainVideoContainerSetting(); +videoSettings.setMainVideoAspectRatio(CometChatCalls.CallSettings.ASPECT_RATIO_CONTAIN); +videoSettings.setFullScreenButtonParams(CometChatCalls.CallSettings.POSITION_BOTTOM_RIGHT, true); +videoSettings.setNameLabelParams(CometChatCalls.CallSettings.POSITION_BOTTOM_LEFT, true, "#333333"); -This section will guide you to customise the main video container. +// Pass to CallSettingsBuilder +new CometChatCalls.CallSettingsBuilder() + .setMainVideoContainerSetting(videoSettings) + .build(); +``` + -## Implementation +## Overview -Once you have decided to implement [Default Calling](/sdk/react-native/default-call) or [Direct Calling](/sdk/react-native/direct-call) calling and followed the steps to implement them. Just few additional methods will help you quickly customize the main video container. +This section guides you through customizing the main video container in your call UI. -Please make sure your callSettings is configured accordingly for [Default Calling](/sdk/react-native/default-call) or [Direct Calling](/sdk/react-native/direct-call). +Once you have decided to implement [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call) calling and followed the steps to implement them, a few additional methods will help you quickly customize the main video container. + +Please make sure your callSettings is configured accordingly for [Ringing](/sdk/react-native/default-call) or [Call Session](/sdk/react-native/direct-call). ## Main Video Container Setting -The `MainVideoContainerSetting` Class is the required in case you want to customise the main video view. You need to pass the Object of the `MainVideoContainerSetting` Class in the `setMainVideoContainerSetting()` method of the `CallSettingsBuilder`. +The `MainVideoContainerSetting` class is required when you want to customise the main video view. You need to pass the object of the `MainVideoContainerSetting` class in the `setMainVideoContainerSetting()` method of the `CallSettingsBuilder`. | Setting | Description | | ------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -40,3 +55,47 @@ videoSettings.setUserListButtonParams(CometChatCalls.CallSettings.POSITION_BOTTO + +## Best Practices + + + + Avoid placing multiple buttons in the same corner position. Overlapping controls can make the UI confusing and hard to interact with. Spread controls across different corners for a clean layout. + + + The `ASPECT_RATIO_CONTAIN` mode ensures the full video frame is visible without cropping. Use `ASPECT_RATIO_COVER` only when you want the video to fill the container and are okay with some edges being clipped. + + + Video container customizations can look different across devices. Test your button positions and label visibility on both small phones and larger tablets to ensure a consistent experience. + + + +## Troubleshooting + + + + Ensure you pass the `MainVideoContainerSetting` object to `setMainVideoContainerSetting()` on the `CallSettingsBuilder` before calling `.build()`. Settings applied after building won't take effect. + + + Check that the `visibility` parameter is set to `true` for the button you want to show. Also verify that `enableDefaultLayout(true)` is set in your `CallSettingsBuilder`, as custom video settings work alongside the default layout. + + + +--- + +## Next Steps + + + + Start and manage call sessions with full configuration options + + + Record call sessions for playback and compliance + + + Enable screen sharing and presenter layouts in calls + + + Implement a complete calling experience with incoming and outgoing call UI + + \ No newline at end of file