diff --git a/.gitignore b/.gitignore index 4669a449e..2b6c95161 100644 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ __pycache__/ /docs-templates /docs-test-suite /prompts +/docs-comparison-tool diff --git a/docs.json b/docs.json index 30be5bb91..6845553b3 100644 --- a/docs.json +++ b/docs.json @@ -884,7 +884,29 @@ "group": " ", "pages": [ "ui-kit/react-native/overview", - "ui-kit/react-native/getting-started", + { + "group": "Getting Started", + "pages": [ + { + "group": "React Native CLI", + "pages": [ + "ui-kit/react-native/react-native-cli-integration", + "ui-kit/react-native/react-native-conversation", + "ui-kit/react-native/react-native-one-to-one-chat", + "ui-kit/react-native/react-native-tab-based-chat" + ] + }, + { + "group": "Expo", + "pages": [ + "ui-kit/react-native/expo-integration", + "ui-kit/react-native/expo-conversation", + "ui-kit/react-native/expo-one-to-one-chat", + "ui-kit/react-native/expo-tab-based-chat" + ] + } + ] + }, { "group": "Features", "pages": [ @@ -929,33 +951,35 @@ ] }, { - "group": "References", + "group": "Reference", "pages": [ "ui-kit/react-native/methods", "ui-kit/react-native/events" ] }, { - "group": "Advanced", + "group": "Guides", "pages": [ - "ui-kit/react-native/multi-tab-chat-ui-guide", - "ui-kit/react-native/expo-integration-guide", - "ui-kit/react-native/apple-privacy-manifest-guide", + "ui-kit/react-native/guide-overview", + "ui-kit/react-native/guide-ai-agent", + "ui-kit/react-native/guide-new-chat", + "ui-kit/react-native/guide-group-chat", + "ui-kit/react-native/guide-threaded-messages", + "ui-kit/react-native/guide-search-messages", + "ui-kit/react-native/guide-block-unblock-user", + "ui-kit/react-native/custom-text-formatter-guide", "ui-kit/react-native/mentions-formatter-guide", - "ui-kit/react-native/shortcut-formatter-guide" + "ui-kit/react-native/url-formatter-guide", + "ui-kit/react-native/shortcut-formatter-guide", + "ui-kit/react-native/apple-privacy-manifest-guide" ] }, - { - "group": "Guides", - "pages": ["ui-kit/react-native/guide-ai-agent"] - }, { "group": "Migration Guide", "pages": [ - "ui-kit/react-native/upgrading-from-v4", - "ui-kit/react-native/property-changes" + "ui-kit/react-native/upgrading-from-v4" ] - }, + }, "ui-kit/react-native/link/sample", "ui-kit/react-native/link/changelog" ] @@ -2932,7 +2956,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" ] }, @@ -5211,6 +5242,10 @@ "source": "/ui-kit/android/property-changes", "destination": "/ui-kit/android/upgrading-from-v4" }, + { + "source": "/ui-kit/react-native/property-changes", + "destination": "/ui-kit/react-native/upgrading-from-v4" + }, { "source": "/ai/overview", "destination": "/fundamentals/ai-user-copilot/overview" @@ -5904,8 +5939,8 @@ "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" }, { "source": "/sdk/ionic/overview", diff --git a/images/overview_cometchat_screens.png b/images/overview_cometchat_screens.png new file mode 100644 index 000000000..7f68fb614 Binary files /dev/null and b/images/overview_cometchat_screens.png differ diff --git a/images/shortcut_formatter_cometchat_screens.png b/images/shortcut_formatter_cometchat_screens.png new file mode 100644 index 000000000..aeeda4b6f Binary files /dev/null and b/images/shortcut_formatter_cometchat_screens.png differ 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..f5e825e32 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,233 @@ let messagesRequest: CometChat.MessagesRequest = + +**On Success** — `fetchPrevious()` returns an array of `Message` objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25234"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID or GUID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Nice"` | +| `sentAt` | number | Unix timestamp when sent | `1771398092` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771398092` | +| `readAt` | number | Unix timestamp when read | `1771404705` | +| `updatedAt` | number | Unix timestamp when updated | `1771404705` | +| `sender` | object | Sender user details | [See below ↓](#filter-limit-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-limit-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-limit-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#filter-limit-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397762` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Nice"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-limit-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#filter-limit-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-limit-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-limit-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-limit-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-limit-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397762` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-limit-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-limit-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension data | [See below ↓](#filter-limit-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Array of link previews | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-limit-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-limit-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension data | [See below ↓](#filter-limit-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Array of link previews | `[]` | + + + ## Messages for a user conversation *In other words, how do I fetch messages between me and any user* @@ -58,7 +310,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 +332,233 @@ let UID: string = "UID", + +**On Success** — `fetchPrevious()` returns an array of `Message` objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25234"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Nice"` | +| `sentAt` | number | Unix timestamp when sent | `1771398092` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771398092` | +| `readAt` | number | Unix timestamp when read | `1771404705` | +| `updatedAt` | number | Unix timestamp when updated | `1771404705` | +| `sender` | object | Sender user details | [See below ↓](#filter-uid-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-uid-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-uid-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#filter-uid-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397762` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Nice"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-uid-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#filter-uid-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-uid-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-uid-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-uid-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-uid-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771397762` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-uid-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-uid-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#filter-uid-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-uid-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-uid-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#filter-uid-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + + ## Messages for a group conversation *In other words, how do I fetch messages for any group conversation* @@ -87,7 +566,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 +588,148 @@ let GUID: string = "GUID", - + +**On Success** — `fetchPrevious()` returns an array of `Message` objects for the group: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25237"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group's GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Nice"` | +| `sentAt` | number | Unix timestamp when sent | `1771400683` | +| `updatedAt` | number | Unix timestamp when updated | `1771400683` | +| `sender` | object | Sender user details | [See below ↓](#filter-guid-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#filter-guid-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-guid-data-object) | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | -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. +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `2` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Nice"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-guid-data-entities-object) | +| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | + +--- + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-guid-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-guid-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | Contains `uid`, `name`, `avatar`, `status`, `role`, `lastActiveAt`, `tags` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"group"` | +| `entity` | object | Group entity details | [See below ↓](#filter-guid-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `2` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + + + + +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 +737,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 +751,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let UID = "UID"; let messageId = 1; @@ -150,7 +765,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", messageId: number = 1, @@ -165,7 +780,7 @@ let UID: string = "UID", - + ```typescript let UID: string = "UID", messageId: number = 1, @@ -182,6 +797,87 @@ let UID: string = "UID", + +**On Success** — `fetchPrevious()` returns messages before the specified message ID: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25233"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"UnreadHey"` | +| `sentAt` | number | Unix timestamp when sent | `1771398088` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771398088` | +| `readAt` | number | Unix timestamp when read | `1771404705` | +| `updatedAt` | number | Unix timestamp when updated | `1771398088` | +| `sender` | object | Sender user details | [See below ↓](#filter-msgid-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-msgid-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-msgid-data-object) | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397762` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"UnreadHey"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | +| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | + + + 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 +887,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 +901,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let UID = "UID"; let timestamp = 1602221371; @@ -219,7 +915,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID = "UID"; let timestamp = 1602221371; @@ -233,7 +929,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID = "UID"; let timestamp = 1602221371; @@ -249,33 +945,112 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() -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. + +**On Success** — `fetchPrevious()` returns messages before the specified timestamp (includes custom message types): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25191"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"test-custom"` | +| `category` | string | Message category | `"custom"` | +| `customData` | object | Custom message data | [See below ↓](#filter-timestamp-customdata-object) | +| `sentAt` | number | Unix timestamp when sent | `1771324025` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771328175` | +| `readAt` | number | Unix timestamp when read | `1771328175` | +| `updatedAt` | number | Unix timestamp when updated | `1771328175` | +| `sender` | object | Sender user details | [See below ↓](#filter-timestamp-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-timestamp-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-timestamp-data-object) | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | -## Unread messages +--- -*In other words, how do I fetch unread messages* + -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. +**`customData` Object (for custom messages):** - - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() - .setUID(UID) - .setUnread(true) - .setLimit(limit) - .build(); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `greeting` | string | Custom greeting text | `"Hello from custom message!"` | +| `timestamp` | number | Custom timestamp | `1771324022864` | - +--- - -```javascript -let UID = "UID"; -let limit = 30; -let messagesRequest = new CometChat.MessagesRequestBuilder() + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771323567` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771323089` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `customData` | object | Custom message data | Same as top-level `customData` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | +| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | + + + +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 + +*In other words, how do I fetch unread messages* + +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; +let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setUnread(true) .setLimit(limit) @@ -284,8 +1059,8 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - -```typescript + +```javascript let UID = "UID"; let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() @@ -297,7 +1072,21 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + +```typescript +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 +1102,86 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns only unread messages: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25241"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"You there?"` | +| `sentAt` | number | Unix timestamp when sent | `1771413707` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771413707` | +| `updatedAt` | number | Unix timestamp when updated | `1771413707` | +| `sender` | object | Sender user details | [See below ↓](#filter-unread-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-unread-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-unread-data-object) | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771413285` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771413280` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"You there?"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | +| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | + + + 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 +1191,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 +1204,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -348,7 +1217,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -362,7 +1231,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -378,6 +1247,112 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns messages excluding those from blocked users (includes group-call custom messages): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25239"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group's GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"group-call"` | +| `category` | string | Message category | `"custom"` | +| `customData` | object | Custom message data | [See below ↓](#filter-blocked-customdata-object) | +| `sentAt` | number | Unix timestamp when sent | `1771413265` | +| `updatedAt` | number | Unix timestamp when updated | `1771413265` | +| `sender` | object | Sender user details | [See below ↓](#filter-blocked-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#filter-blocked-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-blocked-data-object) | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`customData` Object (for group-call):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `callType` | string | Type of call | `"audio"` | +| `isCaller` | boolean | Whether current user initiated call | `true` | +| `sessionId` | string | Call session identifier | `"v1.in.2748663902141719..."` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771412068` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1748437105` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `customData` | object | Custom message data | Same as top-level `customData` | +| `text` | string | Display text | `"Group video call started. Tap to join!"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | +| `metadata` | object | Injected metadata | Contains `@injected.extensions.link-preview` | +| `moderation` | object | Moderation status | [See below ↓](#filter-blocked-data-moderation-object) | + +--- + + + +**`data.moderation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `status` | string | Moderation status | `"approved"` | + + + 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 +1362,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 +1376,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let UID = "UID"; let limit = 30; @@ -415,7 +1390,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID = "UID"; let limit = 30; @@ -429,7 +1404,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -446,16 +1421,84 @@ let GUID: string = "GUID", + +**On Success** — `fetchNext()` returns messages received or updated after the specified timestamp: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25234"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Nice"` | +| `sentAt` | number | Unix timestamp when sent | `1771398092` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771398092` | +| `readAt` | number | Unix timestamp when read | `1771404705` | +| `updatedAt` | number | Unix timestamp when updated | `1771404705` | +| `sender` | object | Sender user details | [See below ↓](#filter-updatedafter-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-updatedafter-receiver-object) | +| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397762` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + + + 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 +1513,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -485,7 +1528,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -501,7 +1544,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -519,6 +1562,102 @@ let GUID: string = "GUID", + +**On Success** — `fetchNext()` returns only updated messages (e.g., read receipt changes, edits, deletions): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25189"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"image"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Unix timestamp when sent | `1771323061` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771323062` | +| `readAt` | number | Unix timestamp when read | `1771323227` | +| `updatedAt` | number | Unix timestamp when updated | `1771323227` | +| `sender` | object | Sender user details | [See below ↓](#filter-updatesonly-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-updatesonly-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-updatesonly-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771323060` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771322968` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object (for image message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | Media URL | `"https://data-in.cometchat.io/..."` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | File attachments | [See below ↓](#filter-updatesonly-data-attachments-array) | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | +| `moderation` | object | Moderation status | Contains `status: "approved"` | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"png"` | +| `mimeType` | string | MIME type | `"image/png"` | +| `name` | string | File name | `"photo.png"` | +| `size` | number | File size in bytes | `2295572` | +| `url` | string | File URL | `"https://data-in.cometchat.io/..."` | + + + ## Messages for multiple categories *In other words, how do I fetch messages belonging to multiple categories* @@ -528,7 +1667,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 +1681,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -556,7 +1695,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -571,7 +1710,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -588,6 +1727,138 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns messages from the specified categories (includes both `custom` and `message` categories): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25251"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"extension_poll"` or `"text"` | +| `category` | string | Message category | `"custom"` or `"message"` | +| `customData` | object | Custom message data (for custom category) | [See below ↓](#filter-categories-customdata-object) | +| `text` | string | Message text (for text type) | `"Hello Message"` | +| `sentAt` | number | Unix timestamp when sent | `1771474256` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771474256` | +| `readAt` | number | Unix timestamp when read | `1771474256` | +| `updatedAt` | number | Unix timestamp when updated | `1771474256` | +| `sender` | object | Sender user details | [See below ↓](#filter-categories-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-categories-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-categories-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#filter-categories-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`customData` Object (for poll extension):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Poll unique identifier | `"fde49a5e-baa8-4e04-95e9-c2c09557caa0"` | +| `question` | string | Poll question | `"Custom"` | +| `options` | object | Poll options | `{"1": "Yes", "2": "No"}` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771474104` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771474191` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Display text | `"Custom"` or `"Hello Message"` | +| `customData` | object | Custom data (for custom messages) | Same as top-level `customData` | +| `updateConversation` | boolean | Whether to update conversation | `true` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | +| `metadata` | object | Injected metadata | Contains extensions data | + +--- + + + +**`metadata` Object (for poll extension):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-categories-metadata-injected-object) | +| `incrementUnreadCount` | boolean | Whether to increment unread count | `true` | +| `pushNotification` | string | Push notification text | `"Poll: Custom"` | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview data | `{"links": []}` | +| `polls` | object | Poll extension data | [See below ↓](#filter-categories-metadata-polls-object) | + +--- + + + +**`metadata.@injected.extensions.polls` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Poll unique identifier | `"fde49a5e-baa8-4e04-95e9-c2c09557caa0"` | +| `question` | string | Poll question | `"Custom"` | +| `options` | object | Poll options | `{"1": "Yes", "2": "No"}` | +| `results` | object | Poll results | Contains `options` and `total` | + + + 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 +1870,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 +1886,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -631,7 +1902,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let GUID = "GUID"; let limit = 30; @@ -647,7 +1918,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -666,19 +1937,114 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns only media messages (image, video, audio, file types): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25253"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"image"` or `"audio"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Unix timestamp when sent | `1771474540` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771474540` | +| `readAt` | number | Unix timestamp when read | `1771474540` | +| `updatedAt` | number | Unix timestamp when updated | `1771474540` | +| `sender` | object | Sender user details | [See below ↓](#filter-types-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-types-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-types-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771474535` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771474191` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object (for media messages):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Media type | `"image"` or `"audio"` | +| `category` | string | Message category | `"message"` | +| `url` | string | Media URL | `"https://data-in.cometchat.io/..."` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | File attachments | [See below ↓](#filter-types-data-attachments-array) | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"jpg"` or `"ogg"` | +| `mimeType` | string | MIME type | `"image/jpeg"` or `"application/ogg"` | +| `name` | string | File name | `"photo.jpg"` or `"audio.ogg"` | +| `size` | number | File size in bytes | `142099` | +| `url` | string | File URL | `"https://data-in.cometchat.io/..."` | + + + 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 +2055,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 +2069,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 +2084,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 +2101,78 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns messages belonging to the specified thread: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25257"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Thread Message"` | +| `parentMessageId` | string | Parent message ID (thread root) | `"25256"` | +| `sentAt` | number | Unix timestamp when sent | `1771476403` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771476404` | +| `readAt` | number | Unix timestamp when read | `1771476404` | +| `updatedAt` | number | Unix timestamp when updated | `1771476404` | +| `sender` | object | Sender user details | [See below ↓](#filter-thread-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-thread-receiver-object) | +| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771475038` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771475047` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + + + 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 +2180,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 +2193,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -770,7 +2206,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -784,7 +2220,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -800,14 +2236,83 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns messages excluding threaded replies (parent messages with threads still appear): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25256"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` or `"audio"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"New Message for Thread"` | +| `replyCount` | number | Number of replies (for parent messages) | `1` | +| `sentAt` | number | Unix timestamp when sent | `1771476391` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771476392` | +| `readAt` | number | Unix timestamp when read | `1771476392` | +| `updatedAt` | number | Unix timestamp when updated | `1771476392` | +| `sender` | object | Sender user details | [See below ↓](#filter-hidereplies-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-hidereplies-receiver-object) | +| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` or `attachments` | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771475038` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771475047` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + + + ## 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 +2325,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -833,7 +2338,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -847,7 +2352,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -863,6 +2368,76 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns messages excluding deleted messages: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25256"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"New Message for Thread"` | +| `replyCount` | number | Number of replies (if parent message) | `1` | +| `parentMessageId` | string | Parent message ID (if threaded reply) | `"25256"` | +| `sentAt` | number | Unix timestamp when sent | `1771476391` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771476392` | +| `readAt` | number | Unix timestamp when read | `1771476392` | +| `updatedAt` | number | Unix timestamp when updated | `1771476392` | +| `sender` | object | Sender user details | [See below ↓](#filter-hidedeleted-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-hidedeleted-receiver-object) | +| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771475038` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771475047` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + + + ## Messages by tags *In other words, how do I fetch messages by tags* @@ -870,7 +2445,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 +2459,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -898,7 +2473,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -913,7 +2488,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -930,6 +2505,74 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns only messages matching the specified tags: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25259"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Tagged message for docs"` | +| `sentAt` | number | Unix timestamp when sent | `1771478898` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771478900` | +| `readAt` | number | Unix timestamp when read | `1771478900` | +| `updatedAt` | number | Unix timestamp when updated | `1771478900` | +| `sender` | object | Sender user details | [See below ↓](#filter-settags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-settags-receiver-object) | +| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata` | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771478591` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771477541` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + + + ## Messages with tags *In other words, how do I fetch messages with the tags information* @@ -937,7 +2580,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 +2593,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -963,7 +2606,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```typescript let UID: string = "UID", limit: number = 30, @@ -977,7 +2620,7 @@ let UID: string = "UID", - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -993,23 +2636,90 @@ let GUID: string = "GUID", -## Messages with links + +**On Success** — `fetchPrevious()` returns messages with the `tags` field included: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25265"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Tagged message for docs"` | +| `tags` | array | Message tags | `["starredMessage"]` | +| `sentAt` | number | Unix timestamp when sent | `1771481257` | +| `updatedAt` | number | Unix timestamp when updated | `1771481257` | +| `sender` | object | Sender user details | [See below ↓](#filter-withtags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-withtags-receiver-object) | +| `data` | object | Additional message data | Contains `text`, `resource`, `entities`, `metadata`, `moderation` | +| `metadata` | object | Message metadata | Contains `@injected.extensions.link-preview` | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | -In other words, as a logged-in user, how do I fetch messages that contains 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`. + - +**`sender` Object:** -This feature is only available with `Conversation & Advanced Search`. 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) +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771480243` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | - +--- - - -```javascript -let UID = "UID"; -let limit = 30; + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771480251` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + + + +## Messages with 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`. + + + +This feature is only available with `Conversation & Advanced Search`. 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) + + + + + +```javascript +let UID = "UID"; +let limit = 30; let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) .setLimit(limit) @@ -1019,7 +2729,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1062,9 +2772,264 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns an array of `Message` objects containing links: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25269"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Please checkout our website https://cometchat.com"` | +| `sentAt` | number | Unix timestamp when sent | `1771481824` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771481825` | +| `readAt` | number | Unix timestamp when read | `1771481825` | +| `updatedAt` | number | Unix timestamp when updated | `1771481825` | +| `sender` | object | Sender user details | [See below ↓](#filter-haslinks-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-haslinks-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-haslinks-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#filter-haslinks-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771480251` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771480243` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Please checkout our website https://cometchat.com"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-haslinks-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#filter-haslinks-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-haslinks-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-haslinks-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-haslinks-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771480251` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-haslinks-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771480243` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-haslinks-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-haslinks-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension data | [See below ↓](#filter-haslinks-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Array of link previews | [See below ↓](#filter-haslinks-data-metadata-links-array) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview.links` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | The URL found in the message | `"https://cometchat.com"` | +| `title` | string | Page title | `"In-app Chat SDK & API For Messaging And Calling - CometChat"` | +| `description` | string | Page description | `"Build real time chat, voice and video calling experience..."` | +| `favicon` | string | URL to site favicon | `"https://cometchat.com/_static/favicon.png"` | +| `image` | string | URL to preview image | `"https://a.storyblok.com/f/231922/1200x630/d639d0748b/open-graph-image.png/m/1200x630/"` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-haslinks-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-haslinks-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#filter-haslinks-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Array of link previews | [See below ↓](#filter-haslinks-metadata-links-array) | + +--- + + + +**`metadata.@injected.extensions.link-preview.links` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | The URL found in the message | `"https://cometchat.com"` | +| `title` | string | Page title | `"In-app Chat SDK & API For Messaging And Calling - CometChat"` | +| `description` | string | Page description | `"Build real time chat, voice and video calling experience..."` | +| `favicon` | string | URL to site favicon | `"https://cometchat.com/_static/favicon.png"` | +| `image` | string | URL to preview image | `"https://a.storyblok.com/f/231922/1200x630/d639d0748b/open-graph-image.png/m/1200x630/"` | + + + ## 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 +3040,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1088,7 +3053,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1131,9 +3096,170 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns an array of `Message` objects with attachments: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25253"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"image"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Unix timestamp when sent | `1771474540` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771474540` | +| `readAt` | number | Unix timestamp when read | `1771474540` | +| `updatedAt` | number | Unix timestamp when updated | `1771474540` | +| `sender` | object | Sender user details | [See below ↓](#filter-attachments-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-attachments-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-attachments-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771474535` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771474191` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Attachment type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | Array of attachment objects | [See below ↓](#filter-attachments-data-attachments-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-attachments-data-entities-object) | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"jpg"` | +| `mimeType` | string | MIME type of the file | `"image/jpeg"` | +| `name` | string | File name | `"IMG_20260217_150412.jpg"` | +| `size` | number | File size in bytes | `142099` | +| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-attachments-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-attachments-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-attachments-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771474535` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-attachments-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771474191` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + + + ## 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 +3270,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1157,7 +3283,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1200,9 +3326,249 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns an array of `Message` objects with reactions: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25275"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Message with reactions"` | +| `sentAt` | number | Unix timestamp when sent | `1771495045` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771495045` | +| `readAt` | number | Unix timestamp when read | `1771495045` | +| `updatedAt` | number | Unix timestamp when updated | `1771495045` | +| `sender` | object | Sender user details | [See below ↓](#filter-reactions-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-reactions-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-reactions-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#filter-reactions-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Message with reactions"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `reactions` | array | Reactions on the message | [See below ↓](#filter-reactions-data-reactions-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-reactions-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#filter-reactions-data-metadata-object) | + +--- + + + +**`data.reactions` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `reaction` | string | The reaction emoji | `"❤️"` | +| `count` | number | Number of users who reacted | `1` | +| `reactedByMe` | boolean | Whether current user reacted (optional) | `true` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-reactions-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-reactions-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-reactions-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-reactions-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-reactions-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-reactions-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension data | [See below ↓](#filter-reactions-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-reactions-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-reactions-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension data | [See below ↓](#filter-reactions-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + + ## 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 +3579,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1226,7 +3592,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1269,9 +3635,270 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns an array of `Message` objects containing mentions: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25271"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"<@uid:cometchat-uid-2> Hello"` | +| `sentAt` | number | Unix timestamp when sent | `1771482742` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771482743` | +| `readAt` | number | Unix timestamp when read | `1771482743` | +| `updatedAt` | number | Unix timestamp when updated | `1771482743` | +| `sender` | object | Sender user details | [See below ↓](#filter-mentions-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-mentions-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-mentions-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#filter-mentions-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#filter-mentions-mentionedusers-array) | +| `mentionedMe` | boolean | Whether current user is mentioned | `true` | + +--- + + + +**`mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482552` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482544` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"<@uid:cometchat-uid-2> Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `mentions` | object | Map of mentioned users by UID | [See below ↓](#filter-mentions-data-mentions-object) | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-mentions-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#filter-mentions-data-metadata-object) | + +--- + + + +**`data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-mentions-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-mentions-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-mentions-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482552` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-mentions-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482544` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentions-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-mentions-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentions-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentions-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-mentions-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentions-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + + ## 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 +3909,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1295,7 +3922,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1338,9 +3965,270 @@ let GUID: string = "GUID", + +**On Success** — `fetchPrevious()` returns an array of `Message` objects mentioning the specified UIDs: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25271"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"<@uid:cometchat-uid-2> Hello"` | +| `sentAt` | number | Unix timestamp when sent | `1771482742` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771482743` | +| `readAt` | number | Unix timestamp when read | `1771482743` | +| `updatedAt` | number | Unix timestamp when updated | `1771482743` | +| `sender` | object | Sender user details | [See below ↓](#filter-mentioneduid-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-mentioneduid-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-mentioneduid-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#filter-mentioneduid-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#filter-mentioneduid-mentionedusers-array) | +| `mentionedMe` | boolean | Whether current user is mentioned | `true` | + +--- + + + +**`mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482552` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482544` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"<@uid:cometchat-uid-2> Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `mentions` | object | Map of mentioned users by UID | [See below ↓](#filter-mentioneduid-data-mentions-object) | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-mentioneduid-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#filter-mentioneduid-data-metadata-object) | + +--- + + + +**`data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-mentioneduid-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-mentioneduid-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-mentioneduid-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482552` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-mentioneduid-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771482544` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentioneduid-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-mentioneduid-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentioneduid-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#filter-mentioneduid-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#filter-mentioneduid-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#filter-mentioneduid-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + + ## 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 +4239,7 @@ This feature is only available with `Conversation & Advanced Search`. The `Conve - + ```javascript let UID = "UID"; let limit = 30; @@ -1364,7 +4252,7 @@ let messagesRequest = new CometChat.MessagesRequestBuilder() - + ```javascript let GUID = "GUID"; let limit = 30; @@ -1406,3 +4294,211 @@ let GUID: string = "GUID", + + +**On Success** — `fetchPrevious()` returns an array of `Message` objects with the specified attachment types: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25196"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"image"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Unix timestamp when sent | `1771386517` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771386517` | +| `readAt` | number | Unix timestamp when read | `1771483750` | +| `updatedAt` | number | Unix timestamp when updated | `1771483750` | +| `sender` | object | Sender user details | [See below ↓](#filter-attachmenttypes-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#filter-attachmenttypes-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#filter-attachmenttypes-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771386507` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771386436` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Attachment type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | Array of attachment objects | [See below ↓](#filter-attachmenttypes-data-attachments-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#filter-attachmenttypes-data-entities-object) | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extension` | string | File extension | `"jpg"` | +| `mimeType` | string | MIME type of the file | `"image/jpeg"` | +| `name` | string | File name | `"IMG_20260217_150412.jpg"` | +| `size` | number | File size in bytes | `142099` | +| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/2748663902141719/media/..."` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#filter-attachmenttypes-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#filter-attachmenttypes-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-attachmenttypes-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771386507` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#filter-attachmenttypes-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771386436` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + + + +## 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..2afe70562 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,163 @@ 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); - } -); -``` + }, + (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); + } + ); + ``` + + - +| Parameter | Description | +| --------- | ------------------------------------------------ | +| UID | The UID of the user that you would like to login | +| authKey | CometChat Auth Key | - -```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: CometChat.CometChatException) => { - console.log("Some Error Occured", { error }); - } -); -``` +After the user logs in, their information is returned in the `User` object on `Promise` resolved. - + +**On Success** — Returns a User object: - + -| Parameters | Description | -| ---------- | ------------------------------------------------ | -| UID | The UID of the user that you would like to login | -| authKey | CometChat Auth Key | +**User Object:** -After the user logs in, their information is returned in the `User` object on `Promise` resolved. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | +| `name` | string | Display name of the user | `"George Alan"` | +| `authToken` | string | Authentication token for the session | `"cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Current online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771311515` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Unix timestamp if user is deactivated (0 if active) | `0` | +| `tags` | array | Tags associated with the user | `[]` | + + ## 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 +200,98 @@ CometChat.getLoggedinUser().then( After the user logs in, their information is returned in the `User` object on the `Promise` resolved. -## Logout + +**On Success** — Returns a User object: -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 }); - } -); -``` +**User Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user | `"cometchat-uid-2"` | +| `name` | string | Display name of the user | `"George Alan"` | +| `authToken` | string | Authentication token for the session | `"cometchat-uid-2_17713124898af10df254d51ef6ffc14e79955ac0"` | +| `avatar` | string | URL to user's avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Current online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771311515` | +| `hasBlockedMe` | boolean | Whether this user has blocked the logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked this user | `false` | +| `deactivatedAt` | number | Unix timestamp if user is deactivated (0 if active) | `0` | +| `tags` | array | Tags associated with the user | `[]` | - -```javascript -CometChat.logout().then( - (loggedOut: Object) => { - console.log("Logout completed successfully"); - }, - (error: CometChat.CometChatException) => { - console.log("Logout failed with exception:", { error }); - } -); -``` + - +## 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); + } + ); + ``` + + + ```typescript + CometChat.logout().then( + (loggedOut: Object) => { + console.log("Logout completed successfully"); + }, + (error: CometChat.CometChatException) => { + console.log("Logout failed with exception:", error); + } + ); + ``` + + + +**On Success** — Returns a success message: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Logout confirmation | `"Logout completed successfully"` | + + + + + + - 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..413411612 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..8b12fea86 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!"; @@ -66,6 +83,29 @@ CometChat.createGroup(group).then( + +**On Success** — `createGroup()` returns the created Group object: + + + +**Group Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique group identifier | `"group_1772435275327"` | +| `name` | string | Group name | `"Creation"` | +| `type` | string | Group type | `"public"` | +| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | +| `scope` | string | Logged-in user's scope in the group | `"admin"` | +| `membersCount` | number | Number of members in the group | `1` | +| `hasJoined` | boolean | Whether logged-in user has joined | `true` | +| `isBanned` | boolean | Whether logged-in user is banned | `false` | +| `joinedAt` | number | Unix timestamp when user joined | `1772435275` | +| `createdAt` | number | Unix timestamp when group was created | `1772435275` | +| `conversationId` | string | Conversation identifier for the group | `"group_group_1772435275327"` | + + + The createGroup() method takes the following parameters: | Parameter | Description | @@ -76,7 +116,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. @@ -150,6 +190,54 @@ CometChat.createGroupWithMembers(group, members, banMembers).then( + +**On Success** — `createGroupWithMembers()` returns an object with `group` and `members` keys: + + + +**Response Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `group` | object | The created Group object | [See below ↓](#create-group-with-members-group-object) | +| `members` | object | Per-UID results for member additions | [See below ↓](#create-group-with-members-members-object) | + +--- + + + +**`group` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique group identifier | `"group_with_members_1772435203225"` | +| `name` | string | Group name | `"Test Group With Members"` | +| `type` | string | Group type | `"public"` | +| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | +| `scope` | string | Logged-in user's scope in the group | `"admin"` | +| `membersCount` | number | Number of members in the group | `4` | +| `hasJoined` | boolean | Whether logged-in user has joined | `true` | +| `isBanned` | boolean | Whether logged-in user is banned | `false` | +| `joinedAt` | number | Unix timestamp when user joined | `1772435203` | +| `createdAt` | number | Unix timestamp when group was created | `1772435203` | +| `conversationId` | string | Conversation identifier for the group | `"group_group_with_members_1772435203225"` | + +--- + + + +**`members` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `cometchat-uid-1` | string | Result for this UID | `"success"` | +| `cometchat-uid-2` | string | Result for this UID | `"success"` | +| `cometchat-uid-3` | string | Result for this UID | `"success"` | + +Each key is a UID, and the value is either `"success"` or an error message describing why the operation failed. + + + This method returns an Object which has two keys: `group` & `members` . The group key has the Group Object which contains all the information of the group which is created. The members key has the `UID` of the users and the value will either be `success` or an `error` message describing why the operation to add/ban the user failed. ## Group Class @@ -171,3 +259,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..f232ddbe5 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,41 @@ 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. + +**On Success** — `initiateCall()` returns a `Call` object with session details: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"initiated"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009087929026e8ed35bb3c1f9b4aea3d6fe52b63eaa060"` | +| `status` | string | Current call status | `"initiated"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009087` | +| `joinedAt` | number | Unix timestamp when user joined | `1772009087` | +| `id` | string | Unique message ID | `"25329"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who initiated the call | See User Object below | +| `receiver` | object | User receiving the call | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when call was sent | `1772009087` | +| `updatedAt` | number | Unix timestamp of last update | `1772009087` | + +**User Object Structure:** + +| 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | + + + ## 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 +243,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 +257,111 @@ 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. | + +**On Event** — `onIncomingCallReceived` returns a `Call` object (same structure as `initiateCall` response): + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"initiated"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009087929026e8ed35bb3c1f9b4aea3d6fe52b63eaa060"` | +| `status` | string | Current call status | `"initiated"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009087` | +| `joinedAt` | number | Unix timestamp when user joined | `1772009087` | +| `id` | string | Unique message ID | `"25329"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who initiated the call | See User Object below | +| `receiver` | object | User receiving the call | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when call was sent | `1772009087` | +| `updatedAt` | number | Unix timestamp of last update | `1772009087` | + +--- + +**On Event** — `onOutgoingCallRejected` / `onIncomingCallCancelled` returns a `Call` object with `status: "unanswered"`: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"unanswered"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009087929026e8ed35bb3c1f9b4aea3d6fe52b63eaa060"` | +| `status` | string | Current call status | `"unanswered"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009087` | +| `id` | string | Unique message ID | `"25330"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who initiated the call | See User Object below | +| `receiver` | object | User receiving the call | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when call was sent | `1772009132` | +| `updatedAt` | number | Unix timestamp of last update | `1772009132` | + +--- + +**On Event** — `onOutgoingCallAccepted` returns a `Call` object with `status: "ongoing"`: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"ongoing"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | +| `status` | string | Current call status | `"ongoing"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009341` | +| `joinedAt` | number | Unix timestamp when user joined | `1772009347` | +| `id` | string | Unique message ID | `"25332"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who accepted the call | See User Object below | +| `receiver` | object | User receiving the acceptance | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when call was sent | `1772009347` | +| `updatedAt` | number | Unix timestamp of last update | `1772009347` | + +--- + +**On Event** — `onCallEndedMessageReceived` returns a `Call` object with `status: "ended"`: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"ended"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | +| `status` | string | Current call status | `"ended"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009341` | +| `id` | string | Unique message ID | `"25333"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who ended the call | See User Object below | +| `receiver` | object | Other participant | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when call ended | `1772009475` | +| `updatedAt` | number | Unix timestamp of last update | `1772009475` | + +**User Object Structure:** + +| 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | + + + ## Accept Call When an incoming call is received via `onIncomingCallReceived()`, use `acceptCall()` to accept it. On success, start the call session. @@ -235,6 +400,40 @@ CometChat.acceptCall(sessionId).then( + +**On Success** — `acceptCall()` returns a `Call` object with `status: "ongoing"`: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"ongoing"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | +| `status` | string | Current call status | `"ongoing"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009341` | +| `joinedAt` | number | Unix timestamp when user joined | `1772009347` | +| `id` | string | Unique message ID | `"25332"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who accepted the call | See User Object below | +| `receiver` | object | User receiving the acceptance | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when call was sent | `1772009347` | +| `updatedAt` | number | Unix timestamp of last update | `1772009347` | + +**User Object Structure:** + +| 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | + + ## Reject Call Use `rejectCall()` to reject an incoming call. Set the status to `CALL_STATUS_REJECTED`. @@ -273,6 +472,39 @@ CometChat.rejectCall(sessionId, status).then( + +**On Success** — `rejectCall()` with `REJECTED` status returns a `Call` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"rejected"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772011647d5c89acf4865fd17a9e7195bae5cee3e15d0dc34"` | +| `status` | string | Current call status | `"rejected"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011647` | +| `id` | string | Unique message ID | `"25361"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who rejected the call | See User Object below | +| `receiver` | object | User receiving the rejection | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when rejection was sent | `1772011654` | +| `updatedAt` | number | Unix timestamp of last update | `1772011654` | + +**User Object Structure:** + +| 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | + + ## Cancel Call The caller can cancel an outgoing call before it's answered using `rejectCall()` with status `CALL_STATUS_CANCELLED`. @@ -311,6 +543,40 @@ CometChat.rejectCall(sessionId, status).then( + +**On Success** — `rejectCall()` with `CANCELLED` status returns a `Call` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-7"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"cancelled"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009850a11d03ce320d8df8fde2ac7b43a0c30009b954f5"` | +| `status` | string | Current call status | `"cancelled"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772009850` | +| `id` | string | Unique message ID | `"25338"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who cancelled the call | See User Object below | +| `receiver` | object | User who was being called | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when cancellation was sent | `1772009856` | +| `updatedAt` | number | Unix timestamp of last update | `1772009856` | + +**User Object Structure:** + +| 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | + + + ## Start Call Session Once the call is accepted, both participants need to start the call session. @@ -414,8 +680,63 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( + +**On Success** — `generateToken()` returns an object with session and token: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772009341a5f92ad7d21eba0bf840bb6950c7000eb9d5863b"` | +| `token` | string | JWT token for authenticating the call session | `"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImtpZCI6ImNjcHJvX2p3dF9yczI1Nl9rZXkxIn0..."` | + +--- + +**On Event** — `onUserJoined` returns user info when a participant joins: + +| 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"` | +| `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` | +| `id` | string | Internal participant ID | `"03dcf87d"` | +| `joinedAt` | string | Unix timestamp (ms) when user joined | `"1772009349593"` | + +--- + +**On Event** — `onUserListUpdated` returns the current list of participants: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| (array) | array | Array of participant objects | See below | + +Each participant 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"` | + +--- + +**On Event** — `onUserLeft` returns user info when a participant leaves: + +| 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"` | +| `id` | string | Internal participant ID | `"07ba41cd"` | +| `joinedAt` | string | Unix timestamp (ms) when user joined | `"1772010034825"` | +| `isAudioMuted` | boolean | Whether user's audio was muted | `false` | +| `isVideoMuted` | boolean | Whether user's video was muted | `true` | + + 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. @@ -484,6 +805,40 @@ onCallEnded: () => { + +**On Success** — `endCall()` returns a `Call` object with `status: "ended"`: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"ongoing"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.17720117078263785b8e96c36c6a586d6bb3a60e0a6c16d018"` | +| `status` | string | Current call status | `"ended"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011707` | +| `joinedAt` | number | Unix timestamp when user joined | `1772011711` | +| `id` | string | Unique message ID | `"25363"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who ended the call | See User Object below | +| `receiver` | object | Other participant | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when call ended | `1772011711` | +| `updatedAt` | number | Unix timestamp of last update | `1772011711` | + +**User Object Structure:** + +| 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | + + For more details, see the [End Call Session](/sdk/react-native/direct-call#end-call-session) guide. ## Busy Call Handling @@ -522,3 +877,96 @@ CometChat.rejectCall(sessionId, status).then( ``` + + +**On Success** — `rejectCall()` with `BUSY` status returns a `Call` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"busy"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772011351c36eb867b604d0a861952ea718d3d8eaf1c89ec0"` | +| `status` | string | Current call status | `"busy"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011351` | +| `id` | string | Unique message ID | `"25359"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who sent busy status | See User Object below | +| `receiver` | object | User receiving the busy status | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when busy status was sent | `1772011351` | +| `updatedAt` | number | Unix timestamp of last update | `1772011351` | + +--- + +**On Event** — The caller receives `onOutgoingCallRejected` with `status: "busy"`: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | UID of the call recipient | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Current call action | `"busy"` | +| `sessionId` | string | Unique session identifier for the call | `"v1.in.2748663902141719.1772011351c36eb867b604d0a861952ea718d3d8eaf1c89ec0"` | +| `status` | string | Current call status | `"busy"` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772011351` | +| `id` | string | Unique message ID | `"25359"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who sent busy status | See User Object below | +| `receiver` | object | User receiving the busy status | See User Object below | +| `callInitiator` | object | User who started the call | See User Object below | +| `callReceiver` | object | Intended call recipient | See User Object below | +| `sentAt` | number | Unix timestamp when busy status was sent | `1772011351` | +| `updatedAt` | number | Unix timestamp of last update | `1772011351` | + +**User Object Structure:** + +| 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | + + + + + + - 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..0e0eecfac 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,15 @@ CometChat.deleteConversation(GUID, type).then( + +**On Success** — `deleteConversation()` returns a success message: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Confirmation message | `"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 +105,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..fb205d5c9 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"; @@ -41,8 +52,58 @@ CometChat.deleteGroup(GUID).then( + +**On Success** — `deleteGroup()` returns a boolean: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `response` | boolean | Indicates successful deletion | `true` | + + + 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..197fff172 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,151 @@ 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: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25305"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Unix timestamp when originally sent | `1771996215` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771996215` | +| `readAt` | number | Unix timestamp when read | `1771996215` | +| `deletedAt` | number | Unix timestamp when deleted | `1771996222` | +| `deletedBy` | string | UID of user who deleted the message | `"cometchat-uid-7"` | +| `updatedAt` | number | Unix timestamp when updated | `1771996222` | +| `sender` | object | Sender user details | [See below ↓](#delete-message-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#delete-message-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#delete-message-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771993054` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771994056` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entities` | object | Sender and receiver entities | [See below ↓](#delete-message-data-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#delete-message-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#delete-message-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#delete-message-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771993054` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#delete-message-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771994056` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + + + +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 +236,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 +270,308 @@ CometChat.addMessageListener( + +**On Event** — `onMessageDeleted` callback receives the deleted message object: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25301"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Unix timestamp when originally sent | `1771996032` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771996033` | +| `readAt` | number | Unix timestamp when read | `1771996033` | +| `deletedAt` | number | Unix timestamp when deleted | `1771996040` | +| `deletedBy` | string | UID of user who deleted the message | `"cometchat-uid-6"` | +| `updatedAt` | number | Unix timestamp when updated | `1771996040` | +| `sender` | object | Sender user details | [See below ↓](#on-message-deleted-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#on-message-deleted-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#on-message-deleted-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771994056` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771993054` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entities` | object | Sender and receiver entities | [See below ↓](#on-message-deleted-data-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#on-message-deleted-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#on-message-deleted-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#on-message-deleted-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771994056` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#on-message-deleted-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771993054` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + + + + +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: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25301"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Unix timestamp when originally sent | `1771996032` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771996033` | +| `readAt` | number | Unix timestamp when read | `1771996033` | +| `deletedAt` | number | Unix timestamp when deleted | `1771996040` | +| `deletedBy` | string | UID of user who deleted the message | `"cometchat-uid-6"` | +| `updatedAt` | number | Unix timestamp when updated | `1771996040` | +| `sender` | object | Sender user details | [See below ↓](#missed-delete-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#missed-delete-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#missed-delete-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771994056` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771993054` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entities` | object | Sender and receiver entities | [See below ↓](#missed-delete-data-entities-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#missed-delete-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-delete-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#missed-delete-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771994056` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#missed-delete-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771993054` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + + + 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 +579,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..854168bc1 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: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `messageId` | string | ID of the message marked as delivered | `"25323"` | +| `type` | string | Message 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: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `messageId` | string | ID of the message marked as read | `"25323"` | +| `type` | string | Message 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,127 @@ CometChat.markMessageAsUnread(message).then( + +**On Success** — `markMessageAsUnread()` returns the updated `Conversation` object with the new unread count: + + + +**Conversation Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMessageCount` | number | Number of unread messages | `1` | +| `unreadMentionsCount` | number | Number of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25323"` | +| `latestMessageId` | string | ID of latest message | `""` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#mark-unread-lastmessage-object) | +| `conversationWith` | object | User or group the conversation is with | [See below ↓](#mark-unread-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25326"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello <@uid:cometchat-uid-7>, this is a test mention!"` | +| `sentAt` | number | Unix timestamp when sent | `1772006074` | +| `deliveredAt` | number | Unix timestamp when delivered | `1772006158` | +| `readAt` | number | Unix timestamp when read | `1772006158` | +| `updatedAt` | number | Unix timestamp when updated | `1772006158` | +| `mentionedMe` | boolean | Whether current user is mentioned | `true` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#mark-unread-mentionedusers-array) | +| `sender` | object | Sender user details | [See below ↓](#mark-unread-lastmessage-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#mark-unread-lastmessage-receiver-object) | +| `reactions` | array | Message reactions | `[]` | + +--- + + + +**`lastMessage.mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772004288` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`conversationWith` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772004288` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | +| `conversationId` | string | Conversation identifier | `"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 +683,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 +743,159 @@ CometChat.addMessageListener( + +**On Event** — `onMessagesDelivered` returns a `MessageReceipt` object for user conversations: + + + +**MessageReceipt Object (onMessagesDelivered):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiptType` | string | Type of receipt | `"delivery"` | +| `messageId` | string | ID of the message | `"25323"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `receiver` | string | Receiver's UID | `"cometchat-uid-6"` | +| `deliveredAt` | number | Unix timestamp when delivered | `1772005348` | +| `timestamp` | number | Event timestamp | `1772005348` | +| `sender` | object | User who triggered the receipt | [See below ↓](#on-delivered-sender-object) | + +--- + + + +**`sender` Object (onMessagesDelivered):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771853565` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + +**On Event** — `onMessagesRead` returns a `MessageReceipt` object for user conversations: + + + +**MessageReceipt Object (onMessagesRead):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiptType` | string | Type of receipt | `"read"` | +| `messageId` | string | ID of the message | `"25323"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `receiver` | string | Receiver's UID | `"cometchat-uid-6"` | +| `readAt` | number | Unix timestamp when read | `1772005377` | +| `timestamp` | number | Event timestamp | `1772005377` | +| `sender` | object | User who triggered the receipt | [See below ↓](#on-read-sender-object) | + +--- + + + +**`sender` Object (onMessagesRead):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771853565` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + +**On Event** — `onMessagesDeliveredToAll` returns a `MessageReceipt` object for group conversations (sender is System): + + + +**MessageReceipt Object (onMessagesDeliveredToAll):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiptType` | string | Type of receipt | `"deliveredToAll"` | +| `messageId` | string | ID of the message | `"25325"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `receiver` | string | Group GUID | `"tg1"` | +| `deliveredAt` | number | Unix timestamp when delivered to all | `1772005516` | +| `timestamp` | number | Event timestamp | `1772005516` | +| `sender` | object | System user object | [See below ↓](#on-delivered-all-sender-object) | + +--- + + + +**`sender` Object (onMessagesDeliveredToAll):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | System user identifier | `"app_system"` | +| `name` | string | System user name | `"System"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + +**On Event** — `onMessagesReadByAll` returns a `MessageReceipt` object for group conversations (sender is System): + + + +**MessageReceipt Object (onMessagesReadByAll):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiptType` | string | Type of receipt | `"readByAll"` | +| `messageId` | string | ID of the message | `"25325"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `receiver` | string | Group GUID | `"tg1"` | +| `readAt` | number | Unix timestamp when read by all | `1772005546` | +| `timestamp` | number | Event timestamp | `1772005546` | +| `sender` | object | System user object | [See below ↓](#on-read-all-sender-object) | + +--- + + + +**`sender` Object (onMessagesReadByAll):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | System user identifier | `"app_system"` | +| `name` | string | System user name | `"System"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + + + + +**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 +916,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 +967,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..0ae7b7815 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). @@ -68,6 +91,20 @@ CometChatCalls.generateToken(sessionId, userAuthToken).then( | `sessionId` | The unique random session ID. In case you are using the ringing flow, the session ID is available in the `Call` object. | | `userAuthToken` | The user auth token is the logged-in user auth token which you can get by calling CometChat Chat SDK method `CometChat.getLoggedinUser().getAuthToken()` | + +**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. @@ -89,6 +126,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 +179,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 +225,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 +357,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 | @@ -334,6 +379,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 Ending a call session properly is essential to release media resources (camera, microphone, network connections) and update call state across all participants. The termination process differs based on whether you're using the Ringing flow or Session Only flow. @@ -397,6 +530,212 @@ onCallEndButtonPressed: () => { + +**On Success** — `CometChat.endCall()` returns a `Call` object with the final call status: + + + +**Call Object (Root Level):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `reactions` | array | List of reactions on the call | `[]` | +| `mentionedUsers` | array | List of mentioned users | `[]` | +| `mentionedMe` | boolean | Whether current user was mentioned | `false` | +| `receiverId` | string | UID of the call receiver | `"cometchat-uid-6"` | +| `type` | string | Type of call | `"audio"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `category` | string | Message category | `"call"` | +| `action` | string | Call action | `"ended"` | +| `sessionId` | string | Unique session identifier | `"v1.in.2748663902141719.1772095292a49c6a5198e07f9096447749e87124204d95cfc8"` | +| `status` | string | Current call status | `"ended"` | +| `metadata` | object | Custom metadata attached to the call | `{"new": "metajson"}` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772095292` | +| `id` | string | Unique message ID | `"25424"` | +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | object | User who initiated the call | [See below ↓](#end-call-sender-object) | +| `receiver` | object | User receiving the call | [See below ↓](#end-call-receiver-object) | +| `data` | object | Additional call data | [See below ↓](#end-call-data-object) | +| `sentAt` | number | Unix timestamp when call message was sent | `1772095553` | +| `updatedAt` | number | Unix timestamp of last update | `1772095553` | +| `callInitiator` | object | User who initiated the call | [See below ↓](#end-call-initiator-object) | +| `callReceiver` | object | User receiving the call | [See below ↓](#end-call-call-receiver-object) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `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` | +| `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"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772094890` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `tags` | array | Tags associated with the user | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `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` | +| `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"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772094886` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `tags` | array | Tags associated with the user | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `action` | string | Call action type | `"ended"` | +| `entities` | object | Entity details for the call | [See below ↓](#end-call-data-entities-object) | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-3e152d60-8e2b-435b-86cd-0c0fe3bbc6e1-1772094888945"` | + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `by` | object | User who performed the action | [See below ↓](#end-call-data-entities-by-object) | +| `for` | object | User the action was performed for | [See below ↓](#end-call-data-entities-for-object) | +| `on` | object | The call entity | [See below ↓](#end-call-data-entities-on-object) | + + + +**`data.entities.by` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | User entity details | [See below ↓](#end-call-data-entities-by-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + + + +**`data.entities.by.entity` 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772094890` | +| `tags` | array | Tags associated with the user | `[]` | + + + +**`data.entities.for` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | User entity details | [See below ↓](#end-call-data-entities-for-entity-object) | +| `entityType` | string | Type of entity | `"user"` | + + + +**`data.entities.for.entity` 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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772094886` | +| `conversationId` | string | Conversation ID for this user | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | Tags associated with the user | `[]` | + + + +**`data.entities.on` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entity` | object | Call entity details | [See below ↓](#end-call-data-entities-on-entity-object) | +| `entityType` | string | Type of entity | `"call"` | + + + +**`data.entities.on.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sessionid` | string | Unique session identifier | `"v1.in.2748663902141719.1772095292a49c6a5198e07f9096447749e87124204d95cfc8"` | +| `conversationId` | string | Conversation ID | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `sender` | string | UID of the call sender | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `receiver` | string | UID of the call receiver | `"cometchat-uid-6"` | +| `status` | string | Call status | `"ended"` | +| `type` | string | Type of call | `"audio"` | +| `data` | object | Nested call data | `{...}` | +| `initiatedAt` | number | Unix timestamp when call was initiated | `1772095292` | +| `startedAt` | number | Unix timestamp when call started | `1772095302` | +| `endedAt` | number | Unix timestamp when call ended | `1772095553` | +| `duration` | number | Call duration in seconds | `251` | + +--- + + + +**`callInitiator` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `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` | +| `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"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772094890` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `tags` | array | Tags associated with the user | `[]` | + +--- + + + +**`callReceiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `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` | +| `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"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772094886` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `tags` | array | Tags associated with the user | `[]` | + + + **Remote participant** (receives the `onCallEnded()` callback): Call `CometChat.clearActiveCall()` to clear the local call state, then call `CometChatCalls.endSession()` to release media resources. @@ -455,6 +794,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. @@ -617,6 +957,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. @@ -637,3 +999,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..863aaf2b4 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,11 +115,179 @@ CometChat.editMessage(textMessage).then( } ); ``` - - + +**On Success** — `editMessage()` returns the edited message object with `editedAt` and `editedBy` fields: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25652"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Edited message text content | `"Nice, Any Update?"` | +| `sentAt` | number | Unix timestamp when originally sent | `1772446840` | +| `editedAt` | number | Unix timestamp when edited | `1772446861` | +| `editedBy` | string | UID of user who edited the message | `"cometchat-uid-6"` | +| `deliveredAt` | number | Unix timestamp when delivered | `1772446841` | +| `readAt` | number | Unix timestamp when read | `1772446841` | +| `updatedAt` | number | Unix timestamp when updated | `1772446841` | +| `sender` | object | Sender user details | [See below ↓](#edit-message-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#edit-message-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#edit-message-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#edit-message-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772446655` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772446782` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Nice, Any Update?"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#edit-message-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#edit-message-data-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#edit-message-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#edit-message-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#edit-message-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1772446655` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#edit-message-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1772446782` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `edited` | boolean | Indicates message was edited | `true` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `edited` | boolean | Indicates message was edited | `true` | + + + 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. By default, CometChat allows certain roles to edit a message. @@ -120,10 +303,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 +319,6 @@ new CometChat.MessageListener({ }) ); ``` - @@ -152,18 +334,360 @@ new CometChat.MessageListener({ }) ); ``` - - + +**On Event** — `onMessageEdited` callback receives the edited message object: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25652"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Edited message text content | `"Nice, Any Update?"` | +| `sentAt` | number | Unix timestamp when originally sent | `1772446840` | +| `editedAt` | number | Unix timestamp when edited | `1772446861` | +| `editedBy` | string | UID of user who edited the message | `"cometchat-uid-6"` | +| `deliveredAt` | number | Unix timestamp when delivered | `1772446841` | +| `readAt` | number | Unix timestamp when read | `1772446841` | +| `updatedAt` | number | Unix timestamp when updated | `1772446841` | +| `sender` | object | Sender user details | [See below ↓](#on-message-edited-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#on-message-edited-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#on-message-edited-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#on-message-edited-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772446655` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772446782` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Nice, Any Update?"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#on-message-edited-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#on-message-edited-data-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#on-message-edited-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#on-message-edited-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#on-message-edited-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1772446655` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#on-message-edited-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1772446782` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `edited` | boolean | Indicates message was edited | `true` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `edited` | boolean | Indicates message was edited | `true` | + + + + +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. + + +**When fetching message history** — edited messages have `editedAt` and `editedBy` fields set: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25652"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Edited message text content | `"Nice, Any Update?"` | +| `sentAt` | number | Unix timestamp when originally sent | `1772446840` | +| `editedAt` | number | Unix timestamp when edited | `1772446861` | +| `editedBy` | string | UID of user who edited the message | `"cometchat-uid-6"` | +| `deliveredAt` | number | Unix timestamp when delivered | `1772446841` | +| `readAt` | number | Unix timestamp when read | `1772446841` | +| `updatedAt` | number | Unix timestamp when updated | `1772446841` | +| `sender` | object | Sender user details | [See below ↓](#missed-edit-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#missed-edit-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#missed-edit-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#missed-edit-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772446655` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** -For the message edited event, in the `Action` object received, the following fields can help you get the relevant information- +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772446782` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Nice, Any Update?"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#missed-edit-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#missed-edit-data-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#missed-edit-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-edit-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#missed-edit-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1772446655` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#missed-edit-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1772446782` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `edited` | boolean | Indicates message was edited | `true` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `edited` | boolean | Indicates message was edited | `true` | + + + +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 +695,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..7193d3ae6 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,23 @@ Before flagging a message, retrieve the list of available flag reasons configure -### Response + +**On Success** — `getFlagReasons()` returns an array of flag reason objects: -The response is an array of flag reason objects: + -```javascript -[ - { "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" } -] -``` +**Flag Reason Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique identifier for the flag reason | `"spam"` | +| `name` | string | Display name of the flag reason | `"Spam"` | +| `description` | string | Detailed description of the reason | `"Repeated, promotional, or irrelevant content"` | +| `createdAt` | number | Unix timestamp when reason was created | `1761627675` | +| `updatedAt` | number | Unix timestamp when reason was last updated | `1761627675` | +| `default` | boolean | Whether this is a default reason | `false` | + + ## Flag a Message @@ -132,6 +156,20 @@ To flag a message, use the `flagMessage()` method with the message ID and a payl + +**On Success** — `flagMessage()` returns a success response: + + + +**Response Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `success` | boolean | Indicates if the flag operation succeeded | `true` | +| `message` | string | Confirmation message with flagged message ID | `"Message 25300 has been flagged successfully."` | + + + ### Parameters | Parameter | Type | Required | Description | @@ -140,15 +178,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 +247,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..d91e61738 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"; @@ -57,6 +71,21 @@ CometChat.addMembersToGroup(GUID, membersList, []).then( It will return a Array which will contain the `UID` of the users and the value will either be `success` or an error message describing why the operation to add the user to the group. + +**On Success** — `addMembersToGroup()` returns an object with each UID as key and result as value: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `[UID]` | string | Result for each UID ("success" or error message) | `"success"` | + +**Example:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `cometchat-uid-7` | string | Result for the added member | `"success"` | + + + ## Real-Time Group Member Added Events *In other words, as a member of a group, how do I know when someone is added to the group when my app is running?* @@ -72,7 +101,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 +150,99 @@ 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. + + + +**On Event** — `onMemberAddedToGroup` listener receives the following parameters: + + + +**Listener Parameters:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | object | Action message object | [See `message` Object ↓](#added-message-object) | +| `userAdded` | object | User who was added | [See `userAdded` Object ↓](#user-added-object) | +| `userAddedBy` | object | User who performed the add | [See `userAddedBy` Object ↓](#user-added-by-object) | +| `userAddedIn` | object | Group to which user was added | [See `userAddedIn` Object ↓](#user-added-in-object) | + +--- + + + +**`message` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"25544"` | +| `conversationId` | string | Conversation ID | `"group_group_1772430752261"` | +| `type` | string | Message type | `"groupMember"` | +| `receiverType` | string | Receiver type | `"group"` | +| `category` | string | Message category | `"action"` | +| `action` | string | Action performed | `"added"` | +| `message` | string | Human-readable action message | `"Henry Marino added Ronald Jerry"` | +| `sentAt` | number | Unix timestamp when sent | `1772430763` | +| `updatedAt` | number | Unix timestamp when updated | `1772430763` | + +--- + + + +**`userAdded` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the added user | `"cometchat-uid-6"` | +| `name` | string | Display name | `"Ronald Jerry"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772430654` | +| `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 deactivated (0 if active) | `0` | + +--- + + + +**`userAddedBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user who added | `"cometchat-uid-7"` | +| `name` | string | Display name | `"Henry Marino"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772430649` | +| `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 deactivated (0 if active) | `0` | + +--- + + + +**`userAddedIn` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"group_1772430752261"` | +| `name` | string | Name of the group | `"Hike"` | +| `type` | string | Type of the group | `"public"` | +| `membersCount` | number | Total members in the group | `2` | +| `hasJoined` | boolean | Whether logged-in user has joined | `false` | +| `isBanned` | boolean | Whether logged-in user is banned | `false` | +| `conversationId` | string | Conversation ID for the group | `"group_group_1772430752261"` | +| `createdAt` | number | Unix timestamp when created | `1772430752` | +| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | +| `onlineMembersCount` | number | Number of online members | `1` | + + + ## 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 +255,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..b1593d084 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"; @@ -60,6 +76,15 @@ This method takes the below parameters: The default scope of any member is `participant`. Only the **Admin** of the group can change the scope of any participant in the group. + +**On Success** — `updateGroupMemberScope()` returns a boolean: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `response` | boolean | Indicates whether the scope was successfully changed | `true` | + + + ## Real-Time 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 running?* @@ -67,7 +92,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 +150,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 +171,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..9809a217a 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"; @@ -63,12 +84,21 @@ The `kickGroupMember()` takes following parameters The kicked user will be no longer part of the group and can not perform any actions in the group, but the kicked user can rejoin the group. + +**On Success** — `kickGroupMember()` returns a boolean: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `response` | boolean | Indicates whether the member was successfully kicked | `true` | + + + ## Ban a Group Member 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"; @@ -113,12 +143,21 @@ The `banGroupMember()` method takes the following parameters: The banned user will be no longer part of the group and can not perform any actions in the group. A banned user cannot rejoin the same group without being unbanned. + +**On Success** — `banGroupMember()` returns a boolean: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `response` | boolean | Indicates whether the member was successfully banned | `true` | + + + ## Unban a Banned Group Member from a Group 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"; @@ -163,6 +202,15 @@ The `unbanGroupMember()` method takes the following parameters The unbanned user can now rejoin the group. + +**On Success** — `unbanGroupMember()` returns a boolean: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `response` | boolean | Indicates whether the member was successfully unbanned | `true` | + + + ## Get List of Banned Members for a Group In order to fetch the list of banned groups members for a group, you can use the `BannedGroupMembersRequest` class. To use this class i.e to create an object of the BannedGroupMembersRequest class, you need to use the `BannedGroupMembersRequestBuilder` class. The `BannedGroupMembersRequestBuilder` class allows you to set the parameters based on which the banned group members are to be fetched. @@ -176,7 +224,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 +252,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 +286,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; @@ -291,6 +339,33 @@ bannedGroupMembersRequest.fetchNext().then( + +**On Success** — `fetchNext()` returns an array of banned `GroupMember` objects: + + + +**Banned GroupMember Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `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` | +| `uid` | string | Unique identifier of the user | `"cometchat-uid-6"` | +| `joinedAt` | number | Unix timestamp when the user originally joined the group | `1772430763` | +| `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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `statusMessage` | string | User's status message | `"Testing CometChat SDK"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772430654` | +| `scope` | string | Member's scope in the group before being banned | `"participant"` | +| `isBanned` | boolean | Whether the user is banned from the group | `true` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `guid` | string | GUID of the group | `"group_1772430752261"` | + + + ## Real-Time 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 running?* @@ -302,7 +377,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 +453,103 @@ CometChat.addGroupListener( + +Always remove group listeners when the component unmounts to prevent memory leaks. +```javascript +CometChat.removeGroupListener("UNIQUE_LISTENER_ID"); +``` + + + +**On Event** — `onGroupMemberBanned` listener receives the following parameters: + + + +**Listener Parameters:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | object | Action message object | [See `message` Object ↓](#banned-message-object) | +| `bannedUser` | object | User who was banned | [See `bannedUser` Object ↓](#banned-user-object) | +| `bannedBy` | object | User who performed the ban | [See `bannedBy` Object ↓](#banned-by-object) | +| `bannedFrom` | object | Group from which user was banned | [See `bannedFrom` Object ↓](#banned-from-object) | + +--- + + + +**`message` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message ID | `"25545"` | +| `conversationId` | string | Conversation ID | `"group_group_1772430752261"` | +| `type` | string | Message type | `"groupMember"` | +| `receiverType` | string | Receiver type | `"group"` | +| `category` | string | Message category | `"action"` | +| `action` | string | Action performed | `"banned"` | +| `message` | string | Human-readable action message | `"Henry Marino banned Ronald Jerry"` | +| `sentAt` | number | Unix timestamp when sent | `1772430770` | +| `updatedAt` | number | Unix timestamp when updated | `1772430770` | + +--- + + + +**`bannedUser` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the banned user | `"cometchat-uid-6"` | +| `name` | string | Display name | `"Ronald Jerry"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772430654` | +| `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 deactivated (0 if active) | `0` | + +--- + + + +**`bannedBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the user who banned | `"cometchat-uid-7"` | +| `name` | string | Display name | `"Henry Marino"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772430649` | +| `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 deactivated (0 if active) | `0` | + +--- + + + +**`bannedFrom` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"group_1772430752261"` | +| `name` | string | Name of the group | `"Hike"` | +| `type` | string | Type of the group | `"public"` | +| `membersCount` | number | Total members in the group | `1` | +| `hasJoined` | boolean | Whether logged-in user has joined | `false` | +| `isBanned` | boolean | Whether logged-in user is banned | `false` | +| `conversationId` | string | Conversation ID for the group | `"group_group_1772430752261"` | +| `createdAt` | number | Unix timestamp when created | `1772430752` | +| `owner` | string | UID of the group owner | `"cometchat-uid-7"` | +| `updatedAt` | number | Unix timestamp when updated | `1772430763` | +| `onlineMembersCount` | number | Number of online members | `2` | + + + ## 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 +576,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..26f7a68eb 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,45 @@ 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: - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Confirmation message | `"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,20 +112,248 @@ 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: + + + +**InteractiveMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25308"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"form"` | +| `category` | string | Message category | `"interactive"` | +| `sentAt` | number | Unix timestamp when sent | `1771998776` | +| `updatedAt` | number | Unix timestamp when updated | `1771998776` | +| `interactiveData` | object | Interactive element data | [See below ↓](#send-interactive-interactivedata-object) | +| `interactionGoal` | object | Goal for tracking interactions | [See below ↓](#send-interactive-interactiongoal-object) | +| `sender` | object | Sender user details | [See below ↓](#send-interactive-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-interactive-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-interactive-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - +--- + + + +**`interactiveData` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `title` | string | Form title | `"Quick Survey"` | +| `formFields` | array | Form field definitions | [See below ↓](#send-interactive-formfields-array) | +| `submitElement` | object | Submit button configuration | [See below ↓](#send-interactive-submitelement-object) | +| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | + +--- + + + +**`interactiveData.formFields` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementType` | string | Type of form element | `"textInput"` | +| `elementId` | string | Unique element identifier | `"field1"` | +| `label` | string | Field label text | `"How was your experience?"` | +| `optional` | boolean | Whether field is optional | `false` | + +--- + + + +**`interactiveData.submitElement` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementType` | string | Type of element | `"button"` | +| `elementId` | string | Unique element identifier | `"submit_btn"` | +| `buttonText` | string | Button display text | `"Submit"` | + +--- + + + +**`interactionGoal` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementIds` | array | Target element IDs for goal | `[]` | +| `type` | string | Goal type | `"anyAction"` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998694` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998700` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `interactiveData` | object | Interactive element data | [See below ↓](#send-interactive-data-interactivedata-object) | +| `interactionGoal` | object | Goal configuration | [See below ↓](#send-interactive-data-interactiongoal-object) | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `allowSenderInteraction` | boolean | Whether sender can interact | `false` | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-interactive-data-entities-object) | + +--- + + + +**`data.interactiveData` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `title` | string | Form title | `"Quick Survey"` | +| `formFields` | array | Form field definitions | `[{"elementType": "textInput", "elementId": "field1", "label": "How was your experience?", "optional": false}]` | +| `submitElement` | object | Submit button configuration | `{"elementType": "button", "elementId": "submit_btn", "buttonText": "Submit"}` | +| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | + +--- + + + +**`data.interactionGoal` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementIds` | array | Target element IDs for goal | `[]` | +| `type` | string | Goal type | `"anyAction"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-interactive-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-interactive-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#send-interactive-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998694` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#send-interactive-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998700` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + + ## Event Listeners @@ -99,21 +366,250 @@ 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: + + + +**InteractiveMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25308"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"form"` | +| `category` | string | Message category | `"interactive"` | +| `sentAt` | number | Unix timestamp when sent | `1771998776` | +| `updatedAt` | number | Unix timestamp when updated | `1771998776` | +| `interactiveData` | object | Interactive element data | [See below ↓](#receive-interactive-interactivedata-object) | +| `interactionGoal` | object | Goal for tracking interactions | [See below ↓](#receive-interactive-interactiongoal-object) | +| `sender` | object | Sender user details | [See below ↓](#receive-interactive-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#receive-interactive-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#receive-interactive-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - +--- + + + +**`interactiveData` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `title` | string | Form title | `"Quick Survey"` | +| `formFields` | array | Form field definitions | [See below ↓](#receive-interactive-formfields-array) | +| `submitElement` | object | Submit button configuration | [See below ↓](#receive-interactive-submitelement-object) | +| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | + +--- + + + +**`interactiveData.formFields` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementType` | string | Type of form element | `"textInput"` | +| `elementId` | string | Unique element identifier | `"field1"` | +| `label` | string | Field label text | `"How was your experience?"` | +| `optional` | boolean | Whether field is optional | `false` | + +--- + + + +**`interactiveData.submitElement` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementType` | string | Type of element | `"button"` | +| `elementId` | string | Unique element identifier | `"submit_btn"` | +| `buttonText` | string | Button display text | `"Submit"` | + +--- + + + +**`interactionGoal` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementIds` | array | Target element IDs for goal | `[]` | +| `type` | string | Goal type | `"anyAction"` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998694` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998700` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `interactiveData` | object | Interactive element data | [See below ↓](#receive-interactive-data-interactivedata-object) | +| `interactionGoal` | object | Goal configuration | [See below ↓](#receive-interactive-data-interactiongoal-object) | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `allowSenderInteraction` | boolean | Whether sender can interact | `false` | +| `entities` | object | Sender and receiver entities | [See below ↓](#receive-interactive-data-entities-object) | + +--- + + + +**`data.interactiveData` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `title` | string | Form title | `"Quick Survey"` | +| `formFields` | array | Form field definitions | `[{"elementType": "textInput", "elementId": "field1", "label": "How was your experience?", "optional": false}]` | +| `submitElement` | object | Submit button configuration | `{"elementType": "button", "elementId": "submit_btn", "buttonText": "Submit"}` | +| `interactableElementIds` | array | IDs of interactable elements | `["submit_btn"]` | + +--- + + + +**`data.interactionGoal` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `elementIds` | array | Target element IDs for goal | `[]` | +| `type` | string | Goal type | `"anyAction"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#receive-interactive-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#receive-interactive-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#receive-interactive-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998694` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#receive-interactive-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771998700` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + + ### On Interaction Goal Completed @@ -122,24 +618,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..5e63ed60f 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 = ""; @@ -53,6 +68,26 @@ The `joinGroup()` method takes the below parameters Once you have joined a group successfully, you can send and receive messages in that group. + +**On Success** — `joinGroup()` returns a `Group` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `membersCount` | number | Total number of members in the group | `2` | +| `isBanned` | boolean | Whether the logged-in user is banned from the group | `false` | +| `guid` | string | Unique identifier of the group | `"group_1772427551785"` | +| `name` | string | Name of the group | `"Comet Group"` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"participant"` | +| `joinedAt` | number | Unix timestamp when the user joined | `1772427667` | +| `conversationId` | string | Conversation ID for the group | `"group_group_1772427551785"` | +| `createdAt` | number | Unix timestamp when the group was created | `1772427556` | +| `owner` | string | UID of the group owner | `"cometchat-uid-6"` | +| `onlineMembersCount` | number | Number of online members in the group | `1` | + + + CometChat keeps a track of the groups joined and you do not need to join the group every time you want to communicate in the group. You can identify if a group is joined using the `hasJoined` parameter in the `Group` object. @@ -64,7 +99,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 +129,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 +144,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..10f359307 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 @@ -47,6 +58,15 @@ CometChat.leaveGroup(GUID).then( Once a group is left, the user will no longer receive any updates or messages pertaining to the group. + +**On Success** — `leaveGroup()` returns a boolean: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `hasLeft` | boolean | Indicates whether the user successfully left the group | `true` | + + + ## Real-time Group Member Left Events *In other words, as a member of a group, how do I know if someone has left it?* @@ -54,7 +74,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 +104,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 +119,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..d05d9cc13 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); +``` + + + +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 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,204 @@ CometChat.sendMessage(textMessage).then( + +**On Success** — `sendMessage()` with mentions returns the sent message object with `mentionedUsers` populated: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25326"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text with mention format | `"Hello <@uid:cometchat-uid-7>, this is a test mention!"` | +| `sentAt` | number | Unix timestamp when sent | `1772006074` | +| `updatedAt` | number | Unix timestamp when updated | `1772006074` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#send-mention-mentionedusers-array) | +| `sender` | object | Sender user details | [See below ↓](#send-mention-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-mention-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-mention-data-object) | +| `reactions` | array | Message reactions | `[]` | + +--- + + + +**`mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772004288` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello <@uid:cometchat-uid-7>, this is a test mention!"` | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-mention-data-entities-object) | +| `mentions` | object | Mentioned users map | [See below ↓](#send-mention-data-mentions-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-mention-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-mention-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#send-mention-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772004288` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#send-mention-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.mentions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `cometchat-uid-7` | object | Mentioned user details keyed by UID | [See below ↓](#send-mention-data-mentions-user-object) | + +--- + + + +**`data.mentions["cometchat-uid-7"]` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | + + + 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 +328,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 +355,7 @@ messagesRequest.fetchPrevious().then( - + ```javascript let GUID = "GUID"; let limit = 30; @@ -176,7 +382,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let UID: string = "UID", limit: number = 30, @@ -205,7 +411,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -236,12 +442,24 @@ messagesRequest.fetchPrevious().then( + +**On Success** — `mentionsWithTagInfo(true)` returns mentioned users with their tags: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `tags` | array | User's 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 +486,7 @@ messagesRequest.fetchPrevious().then( - + ```javascript let GUID = "GUID"; let limit = 30; @@ -296,7 +514,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let UID: string = "UID", limit: number = 30, @@ -326,7 +544,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -358,6 +576,19 @@ messagesRequest.fetchPrevious().then( + +**On Success** — `mentionsWithBlockedInfo(true)` returns mentioned users with blocked relationship info: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `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 +596,68 @@ 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: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `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..103f66e97 100644 --- a/sdk/react-native/messaging-overview.mdx +++ b/sdk/react-native/messaging-overview.mdx @@ -1,12 +1,676 @@ --- 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** — Returns a TextMessage object: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25182"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `text` | string | Message text content | `"Hello"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771320772` | +| `updatedAt` | number | Unix timestamp of last update | `1771320772` | +| `sender` | object | Sender user details | [See below ↓](#send-message-overview-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-message-overview-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-message-overview-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | +| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-message-overview-data-entities-object) | +| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | +| `moderation` | object | Moderation status | [See below ↓](#send-message-overview-data-moderation-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-message-overview-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-message-overview-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#send-message-overview-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#send-message-overview-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.moderation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `status` | string | Moderation status | `"pending"` | + + + +### Receive Messages in Real Time + +Use `CometChat.addMessageListener()` to listen for incoming text, media, and custom messages while your app is running. + + + +**onTextMessageReceived** — Returns a TextMessage object: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25180"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `text` | string | Message text content | `"Hello"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771320657` | +| `updatedAt` | number | Unix timestamp of last update | `1771320657` | +| `sender` | object | Sender user details | [See below ↓](#listener-text-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#listener-text-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#listener-text-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | +| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | + +--- + + + +**`sender` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#listener-text-data-entities-object) | +| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`data.entities` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#listener-text-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#listener-text-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#listener-text-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#listener-text-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object (TextMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + +**onMediaMessageReceived** — Returns a MediaMessage object: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25183"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771320862` | +| `updatedAt` | number | Unix timestamp of last update | `1771320862` | +| `sender` | object | Sender user details | [See below ↓](#listener-media-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#listener-media-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#listener-media-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | + +--- + + + +**`sender` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320859` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | URL to the media file | `"https://data-in.cometchat.io/.../1771320861_514214897_9876c9a3f300f29c8ee619765c1ad768.jpg"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | +| `attachments` | array | Media attachments | [See below ↓](#listener-media-data-attachments-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#listener-media-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/.../1771320861_514214897_9876c9a3f300f29c8ee619765c1ad768.jpg"` | +| `name` | string | File name | `"44.jpg"` | +| `mimeType` | string | MIME type | `"image/jpeg"` | +| `extension` | string | File extension | `"jpg"` | +| `size` | number | File size in bytes | `142099` | + +--- + + + +**`data.entities` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#listener-media-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#listener-media-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#listener-media-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320859` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#listener-media-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object (MediaMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + +**onCustomMessageReceived** — Returns a CustomMessage object: + + + +**CustomMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25191"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `type` | string | Custom message type | `"test-custom"` | +| `category` | string | Message category | `"custom"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771324025` | +| `updatedAt` | number | Unix timestamp of last update | `1771324025` | +| `customData` | object | Custom payload data | [See below ↓](#listener-custom-customdata-object) | +| `sender` | object | Sender user details | [See below ↓](#listener-custom-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#listener-custom-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#listener-custom-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | +| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | + +--- + + + +**`customData` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `greeting` | string | Custom greeting message | `"Hello from custom message!"` | +| `timestamp` | number | Custom timestamp | `1771324022864` | + +--- + + + +**`sender` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323567` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Fallback text | `"Sent a custom message"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `customData` | object | Custom payload data | `{"greeting": "Hello from custom message!", "timestamp": 1771324022864}` | +| `entities` | object | Sender and receiver entities | [See below ↓](#listener-custom-data-entities-object) | +| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`data.entities` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#listener-custom-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#listener-custom-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#listener-custom-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323567` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#listener-custom-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object (CustomMessage):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + + + +## 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..4030ddca1 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..794ac7fc9 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,96 @@ CometChat.addReaction(messageId, emoji) + +**On Success** — `addReaction()` returns the updated message object with the reaction added: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25327"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Message for Reactions"` | +| `sentAt` | number | Unix timestamp when sent | `1772006757` | +| `deliveredAt` | number | Unix timestamp when delivered | `1772006757` | +| `readAt` | number | Unix timestamp when read | `1772006757` | +| `updatedAt` | number | Unix timestamp when updated | `1772006757` | +| `sender` | object | Sender user details | [See below ↓](#add-reaction-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#add-reaction-receiver-object) | +| `data` | object | Additional message data with reactions | [See below ↓](#add-reaction-data-object) | +| `reactions` | array | Message reactions (root level) | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772004288` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Message for Reactions"` | +| `reactions` | array | Reaction counts | [See below ↓](#add-reaction-data-reactions-array) | + +--- + + + +**`data.reactions` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `reaction` | string | Emoji reaction | `"😊"` | +| `count` | number | Number of users who reacted | `1` | +| `reactedByMe` | boolean | Whether current user reacted | `true` | + + + You can react on text message, media message and custom message @@ -86,14 +191,91 @@ CometChat.removeReaction(messageId, emoji) + +**On Success** — `removeReaction()` returns the updated message object with the reaction removed: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25327"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Message for Reactions"` | +| `sentAt` | number | Unix timestamp when sent | `1772006757` | +| `deliveredAt` | number | Unix timestamp when delivered | `1772006757` | +| `readAt` | number | Unix timestamp when read | `1772006757` | +| `updatedAt` | number | Unix timestamp when updated | `1772006757` | +| `sender` | object | Sender user details | [See below ↓](#remove-reaction-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#remove-reaction-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#remove-reaction-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772004288` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Message for Reactions"` | + + + ## 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 +287,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 +309,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 +338,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 +360,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 +379,43 @@ reactionRequest.fetchPrevious().then( + +**On Success** — `fetchNext()` or `fetchPrevious()` returns an array of `MessageReaction` objects: + + + +**MessageReaction Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique reaction identifier | `"20014"` | +| `messageId` | string | ID of the message reacted to | `"25327"` | +| `reaction` | string | Emoji reaction | `"❤️"` | +| `uid` | string | UID of user who reacted | `"cometchat-uid-7"` | +| `reactedAt` | number | Unix timestamp when reacted | `1772007024` | +| `reactedBy` | object | User who reacted | [See below ↓](#fetch-reactions-reactedby-object) | + +--- + + + +**`reactedBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772007237` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + + + + ## 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 +455,99 @@ CometChat.addMessageListener(listenerID, { + +**On Event** — `onMessageReactionAdded` returns the reaction event data: + + + +**Reaction Event Object (onMessageReactionAdded):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `parentMessageId` | null | Parent message ID (null for non-threaded) | `null` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `reaction` | object | Reaction details | [See below ↓](#reaction-added-reaction-object) | + +--- + + + +**`reaction` Object (onMessageReactionAdded):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique reaction identifier | `"20013"` | +| `messageId` | string | ID of the message reacted to | `"25327"` | +| `reaction` | string | Emoji reaction | `"❤️"` | +| `uid` | string | UID of user who reacted | `"cometchat-uid-7"` | +| `reactedAt` | number | Unix timestamp when reacted | `1772006766` | +| `reactedBy` | object | User who reacted | [See below ↓](#reaction-added-reactedby-object) | + +--- + + + +**`reaction.reactedBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | + +--- + +**On Event** — `onMessageReactionRemoved` returns the reaction event data: + + + +**Reaction Event Object (onMessageReactionRemoved):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `parentMessageId` | null | Parent message ID (null for non-threaded) | `null` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `reaction` | object | Reaction details | [See below ↓](#reaction-removed-reaction-object) | + +--- + + + +**`reaction` Object (onMessageReactionRemoved):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique reaction identifier | `"20013"` | +| `messageId` | string | ID of the message | `"25327"` | +| `reaction` | string | Emoji reaction | `"❤️"` | +| `uid` | string | UID of user who removed reaction | `"cometchat-uid-7"` | +| `reactedAt` | number | Unix timestamp when originally reacted | `1772006766` | +| `reactedBy` | object | User who removed reaction | [See below ↓](#reaction-removed-reactedby-object) | + +--- + + + +**`reaction.reactedBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1772005334` | + + + ## Removing a Reaction Listener To stop listening for reaction events, remove the listener as follows: @@ -261,6 +573,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 +598,17 @@ message.getReactions() + +**On Success** — `getReactions()` returns an array of reaction counts: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `reaction` | string | Emoji reaction | `"❤️"` | +| `count` | number | Number of users who reacted | `1` | +| `reactedByMe` | boolean | Whether current user reacted | `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 +618,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 +628,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 +686,76 @@ action + + +**On Success (REACTION_ADDED)** — `updateMessageWithReactionInfo()` returns the updated message. Calling `getReactions()` on it shows: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `reaction` | string | Emoji reaction | `"👍"` | +| `count` | number | Number of users who reacted | `1` | +| `reactedByMe` | boolean | Whether current user reacted | `false` | + +**On Success (REACTION_REMOVED)** — When the last reaction is removed, `getReactions()` returns an empty array: `[]` + + + + +## 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..d9f67a8e5 100644 --- a/sdk/react-native/receive-messages.mdx +++ b/sdk/react-native/receive-messages.mdx @@ -1,560 +1,2733 @@ --- 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"; - -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); - }, - }) -); -``` + + ```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); + }, + }) + ); + ``` + + - - - -```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); - }, - }) -); -``` +| Parameter | Description | +| -------------- | --------------------------------------------- | +| **listenerId** | An ID that uniquely identifies that listener. | + + + +**onTextMessageReceived** — Text message object received via the listener: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25195"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello"` | +| `sentAt` | number | Timestamp when sent | `1771386431` | +| `updatedAt` | number | Timestamp when updated | `1771386431` | +| `sender` | object | Sender user details | [See below ↓](#realtime-text-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#realtime-text-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#realtime-text-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#realtime-text-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386392` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386383` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#realtime-text-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#realtime-text-data-metadata-object) | +| `moderation` | object | Moderation status | [See below ↓](#realtime-text-data-moderation-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#realtime-text-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#realtime-text-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#realtime-text-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386392` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#realtime-text-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386383` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#realtime-text-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#realtime-text-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#realtime-text-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`data.moderation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `status` | string | Moderation status | `"approved"` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#realtime-text-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#realtime-text-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#realtime-text-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + +**onMediaMessageReceived** — Media message object received via the listener: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25196"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `sentAt` | number | Timestamp when sent | `1771386517` | +| `updatedAt` | number | Timestamp when updated | `1771386517` | +| `sender` | object | Sender user details | [See below ↓](#realtime-media-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#realtime-media-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#realtime-media-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771386507` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771386436` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | Media file URL | `"https://data-in.cometchat.io/..."` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | Media attachments | [See below ↓](#realtime-media-data-attachments-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#realtime-media-data-entities-object) | +| `moderation` | object | Moderation status | [See below ↓](#realtime-media-data-moderation-object) | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | File URL | `"https://data-in.cometchat.io/..."` | +| `name` | string | File name | `"photo.jpg"` | +| `mimeType` | string | MIME type | `"image/jpeg"` | +| `extension` | string | File extension | `"jpg"` | +| `size` | number | File size in bytes | `142099` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#realtime-media-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#realtime-media-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#realtime-media-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771386507` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#realtime-media-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771386436` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.moderation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `status` | string | Moderation status | `"approved"` | + +--- + +**onCustomMessageReceived** — Custom message object received via the listener: + + + +**CustomMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25197"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Custom message type | `"test-custom"` | +| `category` | string | Message category | `"custom"` | +| `customData` | object | Custom data payload | [See below ↓](#realtime-custom-customdata-object) | +| `sentAt` | number | Timestamp when sent | `1771386648` | +| `updatedAt` | number | Timestamp when updated | `1771386648` | +| `sender` | object | Sender user details | [See below ↓](#realtime-custom-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#realtime-custom-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#realtime-custom-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#realtime-custom-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386640` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386630` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`customData` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `greeting` | string | Custom greeting text | `"Hello from custom message!"` | +| `timestamp` | number | Custom timestamp | `1771386646780` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Display text | `"Sent a custom message"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `customData` | object | Custom data payload | [See below ↓](#realtime-custom-data-customdata-object) | +| `entities` | object | Sender and receiver entities | [See below ↓](#realtime-custom-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#realtime-custom-data-metadata-object) | +| `moderation` | object | Moderation status | [See below ↓](#realtime-custom-data-moderation-object) | + +--- + + + +**`data.customData` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `greeting` | string | Custom greeting text | `"Hello from custom message!"` | +| `timestamp` | number | Custom timestamp | `1771386646780` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#realtime-custom-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#realtime-custom-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#realtime-custom-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386640` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#realtime-custom-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771386630` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#realtime-custom-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#realtime-custom-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#realtime-custom-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`data.moderation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `status` | string | Moderation status | `"approved"` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#realtime-custom-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#realtime-custom-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#realtime-custom-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + + + +**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); + ``` + + + + +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 + +*In other words, as a recipient, how do I receive messages that I missed when my app was not running?* + +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 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 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. + +### 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); + } + ); + ``` + + + ```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** — Returns an array of missed message objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25211"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Missed Message"` | +| `sentAt` | number | Timestamp when sent | `1771388912` | +| `updatedAt` | number | Timestamp when updated | `1771388912` | +| `sender` | object | Sender user details | [See below ↓](#missed-user-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#missed-user-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#missed-user-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#missed-user-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771388888` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Missed Message"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#missed-user-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#missed-user-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#missed-user-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-user-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#missed-user-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#missed-user-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771388888` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#missed-user-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#missed-user-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | `{"links": []}` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#missed-user-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#missed-user-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#missed-user-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**On Failure — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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); + } + ); + ``` + + + ```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** — Returns an array of missed group message objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25215"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Group Missed"` | +| `sentAt` | number | Timestamp when sent | `1771389682` | +| `updatedAt` | number | Timestamp when updated | `1771389682` | +| `sender` | object | Sender user details | [See below ↓](#missed-group-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#missed-group-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#missed-group-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#missed-group-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Group Missed"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#missed-group-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#missed-group-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#missed-group-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#missed-group-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#missed-group-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"group"` | +| `entity` | object | Group entity details | [See below ↓](#missed-group-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#missed-group-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | `{"link-preview": {"links": []}}` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#missed-group-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#missed-group-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#missed-group-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**On Failure — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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. + +### 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() + .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** — Returns an array of unread message objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25216"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Unread Message"` | +| `sentAt` | number | Timestamp when sent | `1771390060` | +| `deliveredAt` | number | Timestamp when delivered | `1771390061` | +| `updatedAt` | number | Timestamp when updated | `1771390061` | +| `sender` | object | Sender user details | [See below ↓](#unread-user-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#unread-user-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#unread-user-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#unread-user-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771389781` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Unread Message"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#unread-user-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#unread-user-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#unread-user-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#unread-user-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#unread-user-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#unread-user-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771389781` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#unread-user-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | `{"link-preview": {"links": []}}` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#unread-user-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#unread-user-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#unread-user-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**On Failure — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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() + .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** — Returns an array of unread group message objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25217"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Unread Group Message"` | +| `sentAt` | number | Timestamp when sent | `1771390129` | +| `updatedAt` | number | Timestamp when updated | `1771390129` | +| `sender` | object | Sender user details | [See below ↓](#unread-group-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#unread-group-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#unread-group-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#unread-group-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Unread Group Message"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#unread-group-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#unread-group-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#unread-group-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#unread-group-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#unread-group-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"group"` | +| `entity` | object | Group entity details | [See below ↓](#unread-group-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#unread-group-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#unread-group-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#unread-group-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**On Failure — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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. + + +## Message History + +*In other words, as a logged-in user, how do I fetch the complete message history?* + +### 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. + + + + ```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); + } + ); + ``` + + + ```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); + } + ); + ``` + + + +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** — Returns an array of message history objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25220"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Historic 1-1"` | +| `sentAt` | number | Timestamp when sent | `1771390691` | +| `updatedAt` | number | Timestamp when updated | `1771390691` | +| `sender` | object | Sender user details | [See below ↓](#history-user-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#history-user-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#history-user-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#history-user-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771389781` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Historic 1-1"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#history-user-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#history-user-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#history-user-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#history-user-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#history-user-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#history-user-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771389781` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#history-user-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#history-user-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#history-user-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**On Failure — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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() + .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** — Returns an array of group message history objects: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25218"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Historic Message 1"` | +| `sentAt` | number | Timestamp when sent | `1771390631` | +| `updatedAt` | number | Timestamp when updated | `1771390631` | +| `sender` | object | Sender user details | [See below ↓](#history-group-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#history-group-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#history-group-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#history-group-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Historic Message 1"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#history-group-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#history-group-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#history-group-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#history-group-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#history-group-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771388895` | +| `tags` | array | User tags | `[]` | - +--- - + -| Parameter | Description | | -| -------------- | --------------------------------------------- | - | -| **listenerId** | An ID that uniquely identifies that listener. | | +**`data.entities.receiver` Object:** -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. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"group"` | +| `entity` | object | Group entity details | [See below ↓](#history-group-data-entities-receiver-entity-object) | - - -```javascript -var listenerID = "UNIQUE_LISTENER_ID"; +--- -CometChat.removeMessageListener(listenerID); -``` + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | - +--- - -```typescript -let listenerID: string = "UNIQUE_LISTENER_ID"; + -CometChat.removeMessageListener(listenerID); -``` +**`data.metadata` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | - +--- - + -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. +**`metadata` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#history-group-metadata-injected-object) | -## Missed Messages +--- -*In other words, as a recipient, how do I receive messages that I missed when my app was not running?* + -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. +**`metadata.@injected` Object:** -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. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#history-group-metadata-extensions-object) | -Now using the `fetchNext()` method, you can fetch all the messages that were sent to the user when he/she was offline. +--- -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 +**`metadata.@injected.extensions` Object:** - - -```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); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#history-group-metadata-linkpreview-object) | - +--- - -```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); - } -); -``` +**`metadata.@injected.extensions.link-preview` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | - +--- -### 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); - } -); -``` +**On Failure — Error Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error details | `{}` | - -```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); - } -); -``` +## Search Messages - +*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 a string as input. When set, the SDK will fetch messages which match the `searchKeyword`. -## Unread Messages + +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. -*In other words, as a logged-in user, how do I fetch the messages I've not read?* +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). + -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. +| 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 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 searchKeyword = "Hello"; + let messagesRequest = new CometChat.MessagesRequestBuilder() .setUID(UID) - .setUnread(true) .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** — Returns an array of messages matching the search keyword: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25224"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"xq7SearchTest"` | +| `sentAt` | number | Timestamp when sent | `1771392432` | +| `deliveredAt` | number | Timestamp when delivered | `1771392432` | +| `readAt` | number | Timestamp when read | `1771392432` | +| `updatedAt` | number | Timestamp when updated | `1771392432` | +| `sender` | object | Sender user details | [See below ↓](#search-user-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#search-user-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#search-user-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#search-user-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - +--- -### 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); - } -); -``` +**`sender` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771391162` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | - -```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); - } -); -``` + - +**`receiver` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771391157` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | - -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. + - +**`data` Object:** -## Message History +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"xq7SearchTest"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#search-user-data-entities-object) | +| `metadata` | object | Injected metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | -*In other words, as a logged-in user, how do I fetch the complete message history?* +--- -### 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. +**`data.entities` Object:** - - -```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); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | Contains `entityType` and `entity` | +| `receiver` | object | Receiver entity wrapper | Contains `entityType` and `entity` | - - - -```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); - } -); -``` +--- - + - +**`metadata` Object:** -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. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | -### 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); - } -); -``` +**On Failure — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error details | `{}` | + + - +### For a Particular Group - -```typescript -let GUID: string = "GUID", - limit: number = 30, - 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); + } + ); + ``` + -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. - -## Search Messages - -In other words, as a logged-in user, how do I search a message? + + +**On Success** — Returns an array of group messages matching the search keyword: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25225"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"xq8SearchTest"` | +| `sentAt` | number | Timestamp when sent | `1771392513` | +| `updatedAt` | number | Timestamp when updated | `1771392513` | +| `sender` | object | Sender user details | [See below ↓](#search-group-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#search-group-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#search-group-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#search-group-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | -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`. - - +--- -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) +**`sender` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771391162` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | -| Feature | Basic Search | Advance Search | -| ---------------- | ------------ | -------------- | -| Text search | ✅ | ✅ | -| File name search | ❌ | ✅ | -| Mentions search | ❌ | ✅ | -| Mime type search | ❌ | ✅ | +--- -### For a Particular One-on-one Conversation + + +**`receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `2` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1749203133` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | - - -```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() - .setUID(UID) - .setLimit(limit) - .setSearchKeyword(searchKeyword) - .build(); +**`data` Object:** -messagesRequest.fetchPrevious().then( - (messages: CometChat.BaseMessage[]) => { - console.log("Message list fetched:", messages); - }, - (error: CometChat.CometChatException) => { - console.log("Message fetching failed with error:", error); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"xq8SearchTest"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | Contains `sender` and `receiver` wrappers | +| `metadata` | object | Injected metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - +--- - + -### For a Particular Group +**`metadata` Object:** - - -```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); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | `{"extensions": {"link-preview": {"links": []}}}` | - +--- - -```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 Failure — Error Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error details | `{}` | - + ## Unread Message Count @@ -562,399 +2735,538 @@ 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); -``` + + ```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); + } + ); + ``` + + + ```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", - hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForUser(UID, hideMessagesFromBlockedUsers); -``` +It will return an object which will contain the UID as the key and the unread message count as the value. - + - +**On Success** — Returns an object with UID as key and unread count as value: - - -```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); - } -); -``` + - +**Unread Count Object:** - -```typescript -let UID: string = "UID"; +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `{UID}` | number | Unread message count for the specified user | `2` | -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); - } -); -``` +Example: `{"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 — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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); -``` + + ```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); + } + ); + ``` + + + ```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", - hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForGroup(GUID, hideMessagesFromBlockedUsers); -``` +It will return an object which will contain the GUID as the key and the unread message count as the value. - + - +**On Success** — Returns an object with GUID as key and unread count as value: - - -```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); - } -); -``` + - +**Unread Count Object:** - -```typescript -let GUID: string = "GUID"; +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `{GUID}` | number | Unread message count for the specified group | `3` | -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); - } -); -``` +Example: `{"group_1748415903905": 3}` + +--- - + - +**On Failure — Error Object:** -It will return an object which will contain the GUID as the key and the unread message count as the value. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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(); -``` - - + + ```javascript + CometChat.getUnreadMessageCount(); + ``` + + + ```typescript + 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().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); + } + ); + ``` + -If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true: +It returns an object having two keys: - - -```javascript -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` +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 -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCount(hideMessagesFromBlockedUsers); -``` +**On Success** — Returns an object with users and groups unread counts: - + - +**Unread Count Object:** - - -```javascript -CometChat.getUnreadMessageCount().then( - (unreadMessageCountObject) => { - console.log("Unread message count fetched", unreadMessageCountObject); - }, - (error) => { - console.log("Error in getting unread message count", error); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `users` | object | Object with UIDs as keys and unread counts as values | [See below ↓](#unread-count-all-users-object) | +| `groups` | object | Object with GUIDs as keys and unread counts as values | [See below ↓](#unread-count-all-groups-object) | - - - -```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); - } -); -``` +--- - + - +**`users` Object:** -It returns an object having two keys: +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `{UID}` | number | Unread count for each user | `2` | -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. +Example: `{"cometchat-uid-3": 2}` -### 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(); -``` +**`groups` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `{GUID}` | number | Unread count for each group | `2` | - -```typescript -CometChat.getUnreadMessageCountForAllUsers(); -``` +Example: `{"group_1748415903905": 2}` + +--- - + +**On Failure — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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(); + ``` + 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); -``` + + ```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); + } + ); + ``` + + + ```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); + } + ); + ``` + + - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForAllUsers(hideMessagesFromBlockedUsers); -``` +It returns an object which will contain the UID as the key and the unread message count as the value. - + - +**On Success** — Returns an object with UIDs as keys and unread counts as values: - - -```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); - } -); -``` +**Unread Count Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `{UID}` | number | Unread message count for each user | `2` or `3` | - +Example: `{"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. +--- -### 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: +**On Failure — Error Object:** - - -```javascript -CometChat.getUnreadMessageCountForAllGroups(); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error details | `{}` | - + - -```typescript -CometChat.getUnreadMessageCountForAllGroups(); -``` +### 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(); + ``` + 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); -``` + + ```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); + } + ); + ``` + + + ```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); + } + ); + ``` + + - -```typescript -let hideMessagesFromBlockedUsers: boolean = true; -CometChat.getUnreadMessageCountForAllGroups(hideMessagesFromBlockedUsers); -``` +It returns an object which will contain the GUID as the key and the unread message count as the value. - + - +**On Success** — Returns an object with GUIDs as keys and unread counts as values: - - -```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); - } -); -``` +**Unread Count Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `{GUID}` | number | Unread message count for each group | `2` or `5` | - +Example: `{"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 — Error Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_NOT_LOGGED_IN"` | +| `name` | string | Error name | `"Not logged in"` | +| `message` | string | Error message | `"No user is currently logged in."` | +| `details` | object | Additional error 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..f5a7bcc87 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 dd4e00308..98676cea5 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,293 +95,283 @@ let limit: number = 30, .setConversationType(conversationType) .build(); ``` - - -### With User and Group Tags + +**On Success** — `fetchNext()` returns an array of `Conversation` objects (group conversations only): -This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is false. + - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withUserAndGroupTags(true) - .build(); -``` +**Conversation Object (per item in array):** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"group_group_1748415903905"` | +| `conversationType` | string | Type of conversation | `"group"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25243"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25243"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-type-lastmessage-object) | +| `conversationWith` | object | Group details | [See below ↓](#conv-type-conversationwith-group-object) | - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withUserAndGroupTags(true) - .build(); -``` +--- - + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25243"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group's GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Susan here "` | +| `sentAt` | number | Unix timestamp when sent | `1771413931` | +| `updatedAt` | number | Unix timestamp when updated | `1771413931` | +| `sender` | object | Sender user details | [See below ↓](#conv-type-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#conv-type-receiver-group-object) | +| `data` | object | Additional message data | [See below ↓](#conv-type-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-type-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | - +--- -### Set User Tags + -This method fetches user conversations that have the specified tags. +**`lastMessage.sender` Object:** - - -```javascript -let limit = 30; -let userTags = ["tag1"]; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUserTags(userTags) - .build(); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-4"` | +| `name` | string | User's display name | `"Susan Marie"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"admin"` | +| `lastActiveAt` | number | Last active timestamp | `1771413925` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | - +--- - -```typescript -let limit: number = 30, - userTags: Array = ["tag1"], - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUserTags(userTags) - .build(); -``` + + +**`lastMessage.receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `3` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1748415973` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | - +--- - + -### Set Group Tags +**`lastMessage.data` Object:** -This method fetches group conversations that have the specified tags. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Susan here "` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_12-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-type-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-type-data-metadata-object) | - - -```javascript -let limit = 30; -let groupTags = ["tag1"]; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setGroupTags(groupTags) - .build(); -``` +--- - + - -```typescript -let limit: number = 30, - groupTags: Array = ["tag1"], - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setGroupTags(groupTags) - .build(); -``` +**`lastMessage.data.entities` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-type-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-type-data-entities-receiver-object) | - +--- -### 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` +**`lastMessage.data.entities.sender` Object:** - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withTags(true) - .build(); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-type-data-entities-sender-entity-object) | - +--- - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .withTags(true) - .build(); -``` + - +**`lastMessage.data.entities.sender.entity` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-4"` | +| `name` | string | User's display name | `"Susan Marie"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp"` | +| `role` | string | User's role | `"admin"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771413925` | +| `tags` | array | User tags | `[]` | -### Set Tags +--- -This method helps you fetch the conversations based on the specified tags. + - - -```javascript -let limit = 30; -let tags = ["archivedChat"]; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setTags(tags) - .build(); -``` +**`lastMessage.data.entities.receiver` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"group"` | +| `entity` | object | Group entity details | [See below ↓](#conv-type-data-entities-receiver-entity-object) | - -```typescript -let limit: number = 30, - tags: Array = ["archivedChat"], - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setTags(tags) - .build(); -``` +--- - + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `3` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `joinedAt` | number | Timestamp when user joined | `1748415973` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | - +--- -### Include Blocked Users + -This method helps you fetch the conversations of users whom the logged-in user has blocked. +**`lastMessage.data.metadata` Object:** - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setIncludeBlockedUsers(true) - .build(); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-type-data-metadata-injected-object) | - +--- - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setIncludeBlockedUsers(true) - .build(); -``` + - +**`lastMessage.data.metadata.@injected` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-type-data-metadata-extensions-object) | -### With Blocked Info +--- -This method can be used to fetch the blocked information of the blocked user in the `ConversationWith` object. + - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setWithBlockedInfo(true) - .build(); -``` +**`lastMessage.data.metadata.@injected.extensions` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-type-data-metadata-linkpreview-object) | - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setWithBlockedInfo(true) - .build(); -``` +--- - + - +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** -### Search Conversations +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- -This method helps you search a conversation based on User or Group name. + - +**`lastMessage.metadata` Object:** -This feature is only available with `Conversation & Advanced Search`. 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) +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-type-metadata-injected-object) | - +--- - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setSearchKeyword("Hiking") - .build(); -``` + - +**`lastMessage.metadata.@injected` Object:** - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setSearchKeyword("Hiking") - .build(); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-type-metadata-extensions-object) | - +--- - + -### Unread Conversations +**`lastMessage.metadata.@injected.extensions` Object:** -This method helps you fetch unread conversations. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-type-metadata-linkpreview-object) | - +--- -This feature is only available with `Conversation & Advanced Search`. 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) + - +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** - - -```javascript -let limit = 30; -let conversationRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUnread(true) - .build(); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | - +--- - -```typescript -let limit: number = 30, - conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .setUnread(true) - .build(); -``` + - +**`conversationWith` Object (Group):** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1748437105` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + + -### Hide Agentic Conversations +### With User and Group Tags -This method allows you to exclude agent conversations from the conversation list. When set to `true`, conversations with AI agents will be filtered out. +This method can be used to fetch the user/group tags in the `Conversation` Object. By default the value is false. @@ -366,10 +379,9 @@ This method allows you to exclude agent conversations from the conversation list let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setHideAgentic(true) + .withUserAndGroupTags(true) .build(); ``` - @@ -377,17 +389,2310 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() let limit: number = 30, conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setHideAgentic(true) - .build(); + .withUserAndGroupTags(true) + .build(); ``` - - -### Only Agentic Conversations - -This method allows you to fetch only agent conversations. When set to `true`, only conversations with AI agents will be returned in the list. + +`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 an array of `Conversation` objects with user/group tags: + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25276"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25276"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-usrgrptags-lastmessage-object) | +| `conversationWith` | object | User details with tags | [See below ↓](#conv-usrgrptags-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25276"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `sentAt` | number | Unix timestamp when sent | `1771495242` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | +| `readAt` | number | Unix timestamp when read | `1771495244` | +| `updatedAt` | number | Unix timestamp when updated | `1771495244` | +| `sender` | object | Sender user details | [See below ↓](#conv-usrgrptags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-usrgrptags-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-usrgrptags-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-usrgrptags-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-usrgrptags-mentionedusers-array) | +| `mentionedMe` | boolean | Whether current user is mentioned | `true` | + +--- + + + +**`lastMessage.mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771738926` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `["userTag2"]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `["userTag1"]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-usrgrptags-data-mentions-object) | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-usrgrptags-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-usrgrptags-data-metadata-object) | + +--- + + + +**`lastMessage.data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-usrgrptags-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-usrgrptags-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-usrgrptags-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `tags` | array | User tags | `["userTag2"]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-usrgrptags-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `["userTag1"]` | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-usrgrptags-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-usrgrptags-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-usrgrptags-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-usrgrptags-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-usrgrptags-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-usrgrptags-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`conversationWith` Object (User with tags):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771818451` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags (added by withUserAndGroupTags) | `["userTag2"]` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | + + + +### Set User Tags + +This method fetches user conversations that have the specified tags. + + + +```javascript +let limit = 30; +let userTags = ["tag1"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setUserTags(userTags) + .build(); +``` + + + +```typescript +let limit: number = 30, + userTags: Array = ["tag1"], + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setUserTags(userTags) + .build(); +``` + + + + +**On Success** — `fetchNext()` returns an array of `Conversation` objects filtered by user tags: + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"24957"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"24957"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-usertags-lastmessage-object) | +| `conversationWith` | object | User details | [See below ↓](#conv-usertags-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"24955"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Not yet, I will update you if any."` | +| `sentAt` | number | Unix timestamp when sent | `1770973162` | +| `editedAt` | number | Unix timestamp when edited | `1770973219` | +| `editedBy` | string | UID of user who edited | `"cometchat-uid-5"` | +| `updatedAt` | number | Unix timestamp when updated | `1770973219` | +| `sender` | object | Sender user details | [See below ↓](#conv-usertags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-usertags-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-usertags-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-usertags-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | +| `name` | string | User's display name | `"John Paul"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"admin"` | +| `lastActiveAt` | number | Last active timestamp | `1770973064` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `["tag1"]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1770973150` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `["tag1"]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Not yet, I will update you if any."` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-usertags-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-usertags-data-metadata-object) | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-usertags-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-usertags-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-usertags-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | +| `name` | string | User's display name | `"John Paul"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | +| `role` | string | User's role | `"admin"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1770973064` | +| `tags` | array | User tags | `["tag1"]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-usertags-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1770973150` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | +| `tags` | array | User tags | `["tag1"]` | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-usertags-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-usertags-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-usertags-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-usertags-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-usertags-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-usertags-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | +| `name` | string | User's display name | `"John Paul"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771668031` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-5"` | + + + +### Set Group Tags + +This method fetches group conversations that have the specified tags. + + + +```javascript +let limit = 30; +let groupTags = ["tag1"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setGroupTags(groupTags) + .build(); +``` + + + +```typescript +let limit: number = 30, + groupTags: Array = ["tag1"], + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setGroupTags(groupTags) + .build(); +``` + + + + +**On Success** — `fetchNext()` returns an array of `Conversation` objects filtered by group tags: + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"group_group_1748415903905"` | +| `conversationType` | string | Type of conversation | `"group"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25243"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25243"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-grouptags-lastmessage-object) | +| `conversationWith` | object | Group details | [See below ↓](#conv-grouptags-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25243"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `receiverId` | string | Group's GUID | `"group_1748415903905"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Susan here "` | +| `sentAt` | number | Unix timestamp when sent | `1771413931` | +| `updatedAt` | number | Unix timestamp when updated | `1771413931` | +| `sender` | object | Sender user details | [See below ↓](#conv-grouptags-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#conv-grouptags-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-grouptags-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-grouptags-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-4"` | +| `name` | string | User's display name | `"Susan Marie"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-4.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"admin"` | +| `lastActiveAt` | number | Last active timestamp | `1771413925` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object (Group with tags):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `tags` | array | Group tags | `["tag1"]` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `3` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1748415973` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771245340` | + +--- + + + +**`conversationWith` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1748415903905"` | +| `name` | string | Group's display name | `"3 People Group"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1748415903905"` | +| `owner` | string | Group owner's UID | `"123456"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `12` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1748437105` | +| `createdAt` | number | Group creation timestamp | `1748415957` | +| `updatedAt` | number | Group update timestamp | `1771820149` | +| `updatedBy` | string | UID of user who last updated | `"cometchat-uid-2"` | + + + +### 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`. + + + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); +``` + + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .withTags(true) + .build(); +``` + + + + +**On Success** — `fetchNext()` returns an array of `Conversation` objects with conversation tags: + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25276"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25276"` | +| `tags` | array | Conversation tags (added by withTags) | `["archivedChat"]` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-withtags-lastmessage-object) | +| `conversationWith` | object | User details | [See below ↓](#conv-withtags-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25276"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `sentAt` | number | Unix timestamp when sent | `1771495242` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | +| `readAt` | number | Unix timestamp when read | `1771495244` | +| `updatedAt` | number | Unix timestamp when updated | `1771495244` | +| `sender` | object | Sender user details | [See below ↓](#conv-withtags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-withtags-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-withtags-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-withtags-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-withtags-mentionedusers-array) | +| `mentionedMe` | boolean | Whether current user is mentioned | `true` | + +--- + + + +**`lastMessage.mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771738926` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-withtags-data-mentions-object) | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-withtags-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-withtags-data-metadata-object) | + +--- + + + +**`lastMessage.data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-withtags-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-withtags-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-withtags-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-withtags-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-withtags-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-withtags-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-withtags-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-withtags-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-withtags-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-withtags-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771818451` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | + + + +### Set Tags + +This method helps you fetch the conversations based on the specified tags. + + + +```javascript +let limit = 30; +let tags = ["archivedChat"]; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setTags(tags) + .build(); +``` + + + +```typescript +let limit: number = 30, + tags: Array = ["archivedChat"], + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setTags(tags) + .build(); +``` + + + + +**On Success** — `fetchNext()` returns an array of `Conversation` objects filtered by conversation tags: + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25276"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25276"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-settags-lastmessage-object) | +| `conversationWith` | object | User details | [See below ↓](#conv-settags-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25276"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `sentAt` | number | Unix timestamp when sent | `1771495242` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | +| `readAt` | number | Unix timestamp when read | `1771495244` | +| `updatedAt` | number | Unix timestamp when updated | `1771495244` | +| `sender` | object | Sender user details | [See below ↓](#conv-settags-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-settags-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-settags-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-settags-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-settags-mentionedusers-array) | +| `mentionedMe` | boolean | Whether current user is mentioned | `true` | + +--- + + + +**`lastMessage.mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771738926` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-settags-data-mentions-object) | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-settags-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-settags-data-metadata-object) | + +--- + + + +**`lastMessage.data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-settags-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-settags-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-settags-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-settags-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-settags-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-settags-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-settags-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-settags-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-settags-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-settags-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771818451` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | + + + + +**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. + + + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setIncludeBlockedUsers(true) + .build(); +``` + + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setIncludeBlockedUsers(true) + .build(); +``` + + + + +**On Success** — `fetchNext()` returns an array of `Conversation` objects (includes conversations with blocked users): + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25280"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25276"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-blocked-lastmessage-object) | +| `conversationWith` | object | User details | [See below ↓](#conv-blocked-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25280"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello Blocker"` | +| `sentAt` | number | Unix timestamp when sent | `1771820699` | +| `updatedAt` | number | Unix timestamp when updated | `1771820699` | +| `sender` | object | Sender user details | [See below ↓](#conv-blocked-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-blocked-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-blocked-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-blocked-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-blocked-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-blocked-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-blocked-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771818451` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771738926` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello Blocker"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-blocked-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-blocked-data-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-blocked-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-blocked-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-blocked-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-blocked-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-blocked-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#conv-blocked-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771818451` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details with block info | [See below ↓](#conv-blocked-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1771738926` | +| `tags` | array | User tags | `[]` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `hasBlockedMeAt` | number | Timestamp when blocked by user | `0` | +| `blockedAt` | number | Timestamp when blocked | `0` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771738926` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | + + + +### With Blocked Info + +This method can be used to fetch the blocked information of the blocked user in the `ConversationWith` object. + + + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setWithBlockedInfo(true) + .build(); +``` + + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setWithBlockedInfo(true) + .build(); +``` + + + + +**On Success** — `fetchNext()` returns an array of `Conversation` objects with blocked info in `conversationWith`: + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25276"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25276"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-blockedinfo-lastmessage-object) | +| `conversationWith` | object | User details with blocked info | [See below ↓](#conv-blockedinfo-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25276"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-2"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `sentAt` | number | Unix timestamp when sent | `1771495242` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771495244` | +| `readAt` | number | Unix timestamp when read | `1771495244` | +| `updatedAt` | number | Unix timestamp when updated | `1771495244` | +| `sender` | object | Sender user details | [See below ↓](#conv-blockedinfo-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-blockedinfo-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-blockedinfo-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-blockedinfo-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | [See below ↓](#conv-blockedinfo-mentionedusers-array) | +| `mentionedMe` | boolean | Whether current user is mentioned | `true` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-blockedinfo-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-blockedinfo-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-blockedinfo-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.mentionedUsers` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"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 | Last active timestamp | `1771738926` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Message for mentioned users, Hello <@uid:cometchat-uid-2>"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `mentions` | object | Map of mentioned users by UID | [See below ↓](#conv-blockedinfo-data-mentions-object) | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-blockedinfo-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-blockedinfo-data-metadata-object) | + +--- + + + +**`lastMessage.data.mentions` Object (keyed by UID):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-blockedinfo-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-blockedinfo-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-blockedinfo-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771495034` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-blockedinfo-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-2"` | +| `name` | string | User's display name | `"George Alan"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771494233` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-blockedinfo-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-blockedinfo-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-blockedinfo-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`conversationWith` Object (User with blocked info):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771818451` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `true` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `blockedByMeAt` | number | Timestamp when blocked by current user | `1771820668` | +| `blockedAt` | number | Block timestamp | `1771820668` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | + + + +### Search Conversations + +This method helps you search for a conversation based on a User or Group name. + + + +This feature is only available with `Conversation & Advanced Search`. 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) + + + + + +```javascript +let limit = 30; +let conversationRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setSearchKeyword("Hiking") + .build(); +``` + + + +```typescript +let limit: number = 30, + conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .setSearchKeyword("Hiking") + .build(); +``` + + + + +**On Success** — `fetchNext()` returns an array of `Conversation` objects matching the search keyword: + + + +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"group_cometchat-guid-1"` | +| `conversationType` | string | Type of conversation | `"group"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"4791"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"4791"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-search-lastmessage-object) | +| `conversationWith` | object | Group details | [See below ↓](#conv-search-conversationwith-object) | + +--- + + + +**`lastMessage` Object (Action Message):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"4791"` | +| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | +| `receiverId` | string | Group's GUID | `"cometchat-guid-1"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"groupMember"` | +| `category` | string | Message category | `"action"` | +| `action` | string | Action performed | `"kicked"` | +| `message` | string | Action message text | `"John Paul kicked Andrew Joseph"` | +| `sentAt` | number | Unix timestamp when sent | `1753946954` | +| `deliveredAt` | number | Unix timestamp when delivered | `1764150385` | +| `updatedAt` | number | Unix timestamp when updated | `1764150385` | +| `actionBy` | object | User who performed action | [See below ↓](#conv-search-actionby-object) | +| `actionFor` | object | Group the action was for | [See below ↓](#conv-search-actionfor-object) | +| `actionOn` | object | User the action was on | [See below ↓](#conv-search-actionon-object) | +| `sender` | object | Sender user details | Same as `actionBy` | +| `receiver` | object | Receiver group details | Same as `actionFor` | +| `data` | object | Additional message data | [See below ↓](#conv-search-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.actionBy` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | +| `name` | string | User's display name | `"John Paul"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | +| `status` | string | User's online status | `"offline"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1753945410` | +| `createdAt` | number | User creation timestamp | `1746375164` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`lastMessage.actionFor` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"cometchat-guid-1"` | +| `name` | string | Group's display name | `"Hiking Group"` | +| `type` | string | Group type | `"private"` | +| `description` | string | Group description | `"Explore, connect, and chat with fellow outdoor enthusiasts..."` | +| `icon` | string | URL to group icon | `"https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp"` | +| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | +| `owner` | string | Group owner's UID | `"cometchat-uid-5"` | +| `membersCount` | number | Total members in group | `3` | +| `hasJoined` | boolean | Whether current user has joined | `false` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `createdAt` | number | Group creation timestamp | `1746375164` | +| `updatedAt` | number | Group update timestamp | `1753945144` | + +--- + + + +**`lastMessage.actionOn` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-1"` | +| `name` | string | User's display name | `"Andrew Joseph"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `status` | string | User's online status | `"offline"` | +| `statusMessage` | string | User's status message | `"Hey there I'm using CometChat"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1753944766` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-5"` | +| `createdAt` | number | User creation timestamp | `1746375164` | +| `updatedAt` | number | User update timestamp | `1749731589` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `action` | string | Action type | `"kicked"` | +| `entities` | object | Action entities | [See below ↓](#conv-search-data-entities-object) | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `by` | object | User who performed action | [See below ↓](#conv-search-data-entities-by-object) | +| `for` | object | Group the action was for | [See below ↓](#conv-search-data-entities-for-object) | +| `on` | object | User the action was on | [See below ↓](#conv-search-data-entities-on-object) | + +--- + + + +**`lastMessage.data.entities.by` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-search-data-entities-by-entity-object) | + +--- + + + +**`lastMessage.data.entities.by.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-5"` | +| `name` | string | User's display name | `"John Paul"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-5.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `lastActiveAt` | number | Last active timestamp | `1753945410` | +| `createdAt` | number | User creation timestamp | `1746375164` | + +--- + + + +**`lastMessage.data.entities.for` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"group"` | +| `entity` | object | Group entity details | [See below ↓](#conv-search-data-entities-for-entity-object) | + +--- + + + +**`lastMessage.data.entities.for.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"cometchat-guid-1"` | +| `name` | string | Group's display name | `"Hiking Group"` | +| `type` | string | Group type | `"private"` | +| `description` | string | Group description | `"Explore, connect, and chat with fellow outdoor enthusiasts..."` | +| `icon` | string | URL to group icon | `"https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp"` | +| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | +| `owner` | string | Group owner's UID | `"cometchat-uid-5"` | +| `membersCount` | number | Total members in group | `3` | +| `hasJoined` | boolean | Whether current user has joined | `false` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `createdAt` | number | Group creation timestamp | `1746375164` | +| `updatedAt` | number | Group update timestamp | `1753945144` | + +--- + + + +**`lastMessage.data.entities.on` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-search-data-entities-on-entity-object) | + +--- + + + +**`lastMessage.data.entities.on.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-1"` | +| `name` | string | User's display name | `"Andrew Joseph"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-1.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"offline"` | +| `statusMessage` | string | User's status message | `"Hey there I'm using CometChat"` | +| `lastActiveAt` | number | Last active timestamp | `1753944766` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-1_user_cometchat-uid-5"` | +| `createdAt` | number | User creation timestamp | `1746375164` | +| `updatedAt` | number | User update timestamp | `1749731589` | + +--- + + + +**`conversationWith` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"cometchat-guid-1"` | +| `name` | string | Group's display name | `"Hiking Group"` | +| `type` | string | Group type | `"private"` | +| `description` | string | Group description | `"Explore, connect, and chat with fellow outdoor enthusiasts..."` | +| `icon` | string | URL to group icon | `"https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp"` | +| `conversationId` | string | Conversation identifier | `"group_cometchat-guid-1"` | +| `owner` | string | Group owner's UID | `"cometchat-uid-5"` | +| `scope` | string | Current user's scope in group | `"participant"` | +| `membersCount` | number | Total members in group | `3` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1746375164` | +| `createdAt` | number | Group creation timestamp | `1746375164` | +| `updatedAt` | number | Group update timestamp | `1753946955` | + + + +### Unread Conversations + +This method helps you fetch unread conversations. + + + +This feature is only available with `Conversation & Advanced Search`. 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) + + @@ -395,10 +2700,9 @@ This method allows you to fetch only agent conversations. When set to `true`, on let limit = 30; let conversationRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setOnlyAgentic(true) + .setUnread(true) .build(); ``` - @@ -406,19 +2710,282 @@ let conversationRequest = new CometChat.ConversationsRequestBuilder() let limit: number = 30, conversationRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() .setLimit(limit) - .setOnlyAgentic(true) + .setUnread(true) .build(); ``` - - - + +**On Success** — `fetchNext()` returns an array of `Conversation` objects with unread messages: -The `setHideAgentic()` and `setOnlyAgentic()` methods are mutually exclusive. You should only use one of them in a single request builder instance. + - +**Conversation Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"group_group_1762515421478"` | +| `conversationType` | string | Type of conversation | `"group"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"24359"` | +| `unreadMessageCount` | number | Count of unread messages | `2` | +| `latestMessageId` | string | ID of latest message | `"25236"` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-unread-lastmessage-object) | +| `conversationWith` | object | Group details | [See below ↓](#conv-unread-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25236"` | +| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | +| `receiverId` | string | Group's GUID | `"group_1762515421478"` | +| `receiverType` | string | Type of receiver | `"group"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hru"` | +| `sentAt` | number | Unix timestamp when sent | `1771400675` | +| `updatedAt` | number | Unix timestamp when updated | `1771400675` | +| `sender` | object | Sender user details | [See below ↓](#conv-unread-sender-object) | +| `receiver` | object | Receiver group details | [See below ↓](#conv-unread-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-unread-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-unread-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-unread-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-unread-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-unread-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1762515421478"` | +| `name` | string | Group's display name | `"TwoMemberGroup"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | +| `owner` | string | Group owner's UID | `"cometchat-uid-2"` | +| `scope` | string | Current user's scope in group | `"participant"` | +| `membersCount` | number | Total members in group | `3` | +| `onlineMembersCount` | number | Online members count | `2` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1762515534` | +| `createdAt` | number | Group creation timestamp | `1762515421` | +| `updatedAt` | number | Group update timestamp | `1768888876` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hru"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-unread-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-unread-data-metadata-object) | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-unread-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-unread-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-unread-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-unread-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-unread-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-unread-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-3"` | +| `name` | string | User's display name | `"Nancy Grace"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771397739` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"group"` | +| `entity` | object | Group entity details | [See below ↓](#conv-unread-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1762515421478"` | +| `name` | string | Group's display name | `"TwoMemberGroup"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | +| `owner` | string | Group owner's UID | `"cometchat-uid-2"` | +| `scope` | string | Current user's scope in group | `"participant"` | +| `membersCount` | number | Total members in group | `3` | +| `onlineMembersCount` | number | Online members count | `2` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `joinedAt` | number | Timestamp when user joined | `1762515534` | +| `createdAt` | number | Group creation timestamp | `1762515421` | +| `updatedAt` | number | Group update timestamp | `1768888876` | + +--- + + + +**`conversationWith` Object (Group):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Group's unique identifier | `"group_1762515421478"` | +| `name` | string | Group's display name | `"TwoMemberGroup"` | +| `type` | string | Group type | `"public"` | +| `conversationId` | string | Conversation identifier | `"group_group_1762515421478"` | +| `owner` | string | Group owner's UID | `"cometchat-uid-2"` | +| `scope` | string | Current user's scope in group | `"admin"` | +| `membersCount` | number | Total members in group | `3` | +| `onlineMembersCount` | number | Online members count | `1` | +| `hasJoined` | boolean | Whether current user has joined | `true` | +| `isBanned` | boolean | Whether current user is banned | `false` | +| `joinedAt` | number | Timestamp when user joined | `1762515421` | +| `createdAt` | number | Group creation timestamp | `1762515421` | +| `updatedAt` | number | Group update timestamp | `1768888876` | + + 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. @@ -427,85 +2994,344 @@ 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() .setLimit(limit) .build(); -conversationsRequest.fetchNext().then( - conversationList => { - console.log("Conversations list received:", conversationList); - }, error => { - console.log("Conversations list fetching failed with error:", error); - } -); -``` +conversationsRequest.fetchNext().then( + conversationList => { + console.log("Conversations list received:", conversationList); + }, error => { + console.log("Conversations list fetching failed with error:", error); + } +); +``` + + + +```typescript +let limit: number = 30, + conversationsRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() + .setLimit(limit) + .build(); + +conversationsRequest.fetchNext().then( + (conversationList: CometChat.Conversation[]) => { + console.log("Conversations list received:", conversationList); + }, (error: CometChat.CometChatException) => { + console.log("Conversations list fetching failed with error:", error); + } +); +``` + + + +The `Conversation` Object consists of the following fields: + +| Field | Information | +| ------------------ | ----------------------------------------------------------------- | +| conversationId | ID of the conversation. | +| conversationType | Type of conversation. (user/group) | +| 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. | + +## Tag Conversation + +*In other words, as a logged-in user, how do I tag a conversation?* + +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 tag. + +2. `conversationType`: The `conversationType` variable can hold one of the below two values: + + 1. user - Only fetches user conversation. + 2. group - Only fetches group conversations. + +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( + conversation => { + console.log('conversation', conversation); + }, error => { + console.log('error while fetching a conversation', error); + } +); +``` + + + + +**On Success** — `tagConversation()` returns the updated `Conversation` object with the new tags: + + + +**Conversation Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25291"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25291"` | +| `tags` | array | Conversation tags | `["archivedChat"]` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-tag-lastmessage-object) | +| `conversationWith` | object | User details | [See below ↓](#conv-tag-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25291"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello"` | +| `sentAt` | number | Unix timestamp when sent | `1771831336` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | +| `readAt` | number | Unix timestamp when read | `1771832977` | +| `updatedAt` | number | Unix timestamp when updated | `1771832977` | +| `sender` | object | Sender user details | [See below ↓](#conv-tag-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-tag-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-tag-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-tag-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-tag-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-tag-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-tag-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-tag-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-tag-data-metadata-object) | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-tag-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-tag-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-tag-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-tag-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-tag-data-entities-receiver-object) | + +--- + + - +**`lastMessage.data.entities.sender` Object:** - -```typescript -let limit: number = 30, - conversationsRequest: CometChat.ConversationsRequest = new CometChat.ConversationsRequestBuilder() - .setLimit(limit) - .build(); +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-tag-data-entities-sender-entity-object) | -conversationsRequest.fetchNext().then( - (conversationList: CometChat.Conversation[]) => { - console.log("Conversations list received:", conversationList); - }, (error: CometChat.CometChatException) => { - console.log("Conversations list fetching failed with error:", error); - } -); -``` +--- - + - +**`lastMessage.data.entities.sender.entity` Object:** -The `Conversation` Object consists of the following fields: +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `tags` | array | User tags | `[]` | -| Field | Information | -| ------------------ | ----------------------------------------------------------------- | -| conversationId | ID of the conversation. | -| conversationType | Type of conversation. (user/group) | -| lastMessage | Last message the conversation. | -| conversationWith | User or Group object containing the details of the user or group. | -| unreadMessageCount | Unread message count for the conversation. | +--- -## Tag Conversation + -*In other words, as a logged-in user, how do I tag a conversation?* +**`lastMessage.data.entities.receiver` Object:** -To tag a specific conversation, you can use the `tagConversation()` method. The `tagConversation()` method accepts three parameters. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-tag-data-entities-receiver-entity-object) | -1. `conversationWith`: UID/GUID of the user/group whose conversation you want to fetch. +--- -2. `conversationType`: The `conversationType` variable can hold one of the below two values: + - 1. user - Only fetches user conversation. - 2. group - Only fetches group conversations. +**`lastMessage.data.entities.receiver.entity` Object:** -3. `tags`: The `tags` variable will be a list of tags you want to add to a conversation. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | - - -```javascript -let tags = ["archivedChat"]; -CometChat.tagConversation('conversationWith', 'conversationType', tags).then( - conversation => { - console.log('conversation', conversation); - }, error => { - console.log('error while fetching a conversation', error); - } -); -``` +--- - + - +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771834604` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | + + @@ -526,7 +3352,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 => { @@ -536,17 +3362,280 @@ CometChat.getConversation('conversationWith', 'conversationType').then( } ); ``` - - + +**On Success** — `getConversation()` returns the `Conversation` object: + + + +**Conversation Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message | `"25291"` | +| `unreadMessageCount` | number | Count of unread messages | `0` | +| `latestMessageId` | string | ID of latest message | `"25291"` | +| `tags` | array | Conversation tags | `["archivedChat"]` | +| `lastMessage` | object | Last message in conversation | [See below ↓](#conv-single-lastmessage-object) | +| `conversationWith` | object | User details | [See below ↓](#conv-single-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25291"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello"` | +| `sentAt` | number | Unix timestamp when sent | `1771831336` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | +| `readAt` | number | Unix timestamp when read | `1771832977` | +| `updatedAt` | number | Unix timestamp when updated | `1771832977` | +| `sender` | object | Sender user details | [See below ↓](#conv-single-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-single-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-single-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-single-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-single-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-single-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-single-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-single-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-single-data-metadata-object) | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-single-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-single-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-single-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-single-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-single-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-single-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-single-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771834604` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | +| `conversationId` | string | Conversation identifier | `"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 => { @@ -556,13 +3645,313 @@ conversation => { } ); ``` - - + +**On Success** — `getConversationFromMessage()` returns the converted `Conversation` object: + + + +**Conversation Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `conversationId` | string | Unique conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `conversationType` | string | Type of conversation | `"user"` | +| `unreadMentionsCount` | number | Count of unread mentions | `0` | +| `lastReadMessageId` | string | ID of last read message (empty when converted) | `""` | +| `unreadMessageCount` | number | Count of unread messages (0 when converted) | `0` | +| `latestMessageId` | string | ID of latest message (empty when converted) | `""` | +| `lastMessage` | object | The source message converted to lastMessage | [See below ↓](#conv-convert-lastmessage-object) | +| `conversationWith` | object | User details from message receiver | [See below ↓](#conv-convert-conversationwith-object) | + +--- + + + +**`lastMessage` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25291"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello"` | +| `sentAt` | number | Unix timestamp when sent | `1771831336` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | +| `readAt` | number | Unix timestamp when read | `1771832977` | +| `updatedAt` | number | Unix timestamp when updated | `1771832977` | +| `sender` | object | Sender user details | [See below ↓](#conv-convert-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#conv-convert-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#conv-convert-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#conv-convert-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`lastMessage.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-convert-metadata-injected-object) | + +--- + + + +**`lastMessage.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-convert-metadata-extensions-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-convert-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#conv-convert-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#conv-convert-data-metadata-object) | + +--- + + + +**`lastMessage.data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#conv-convert-data-metadata-injected-object) | + +--- + + + +**`lastMessage.data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#conv-convert-data-metadata-extensions-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#conv-convert-data-metadata-linkpreview-object) | + +--- + + + +**`lastMessage.data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`lastMessage.data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#conv-convert-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#conv-convert-data-entities-receiver-object) | + +--- + + + +**`lastMessage.data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-convert-data-entities-sender-entity-object) | + +--- + + + +**`lastMessage.data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`lastMessage.data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#conv-convert-data-entities-receiver-entity-object) | + +--- + + + +**`lastMessage.data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`conversationWith` Object (User):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User 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 e53e581ac..969c4e923 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; @@ -148,7 +162,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; @@ -187,3 +201,73 @@ groupMembersRequest.fetchNext().then( + + +**On Success** — `fetchNext()` returns an array of `GroupMember` objects: + + + +**GroupMember Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `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` | +| `uid` | string | Unique identifier of the user | `"cometchat-uid-7"` | +| `joinedAt` | number | Unix timestamp when the user joined the group | `1772428121` | +| `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"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `statusMessage` | string | User's status message | `"Testing CometChat SDK"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1772427635` | +| `scope` | string | Member's scope in the group (admin, moderator, participant) | `"participant"` | +| `conversationId` | string | Conversation ID between this user and logged-in user | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `guid` | string | GUID of the group | `"group_1772427551785"` | + + + +## 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..b0e6fe768 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() @@ -40,12 +59,33 @@ let groupsRequest: CometChat.GroupsRequest = + +**On Success** — `fetchNext()` with basic limit returns an array of `Group` objects: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"007007"` | +| `name` | string | Display name of the group | `"Bond"` | +| `type` | string | Group type (public, private, password) | `"public"` | +| `owner` | string | UID of the group owner | `"user-b"` | +| `membersCount` | number | Total number of members in the group | `5` | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | +| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | +| `conversationId` | string | Conversation ID for this group | `"group_007007"` | +| `createdAt` | number | Unix timestamp when group was created | `1760001806` | +| `updatedAt` | number | Unix timestamp of last update | `1768398330` | +| `updatedBy` | string | UID of user who last updated the group (if updated) | `"123456"` | +| `description` | string | Group description (if set) | `"Testing group for QA users"` | +| `icon` | string | URL to group icon image (if set) | `"https://images.unsplash.com/..."` | + + + ### Set Search Keyword 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"; @@ -72,12 +112,32 @@ let groupsRequest: CometChat.GroupsRequest = + +**On Success** — `fetchNext()` with search filter returns an array of `Group` objects matching the keyword: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"group_1748350143247"` | +| `name` | string | Display name of the group | `"testmemebrrole"` | +| `type` | string | Group type (public, private, password) | `"public"` | +| `owner` | string | UID of the group owner | `"123456"` | +| `membersCount` | number | Total number of members in the group | `7` | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | +| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | +| `conversationId` | string | Conversation ID for this group | `"group_group_1748350143247"` | +| `createdAt` | number | Unix timestamp when group was created | `1748350143` | +| `updatedAt` | number | Unix timestamp of last update | `1768888876` | +| `description` | string | Group description (if set) | `"Testing group for QA users"` | +| `icon` | string | URL to group icon image (if set) | `"https://images.unsplash.com/..."` | + + + ### Joined Only 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() @@ -99,12 +159,34 @@ let groupsRequest: CometChat.GroupsRequest = + +**On Success** — `fetchNext()` with `joinedOnly(true)` returns groups the user has joined, with additional fields: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"tg1"` | +| `name` | string | Display name of the group | `"Touring Group"` | +| `type` | string | Group type (public, private, password) | `"public"` | +| `owner` | string | UID of the group owner | `"app_system"` | +| `membersCount` | number | Total number of members in the group | `2` | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | `true` | +| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | +| `scope` | string | User's scope/role in the group (participant, admin, moderator) | `"participant"` | +| `joinedAt` | number | Unix timestamp when user joined the group | `1771829827` | +| `onlineMembersCount` | number | Number of online members in the group | `2` | +| `conversationId` | string | Conversation ID for this group | `"group_tg1"` | +| `createdAt` | number | Unix timestamp when group was created | `1771829812` | +| `updatedAt` | number | Unix timestamp of last update | `1771829832` | +| `icon` | string | URL to group icon image (if set) | `"https://static.vecteezy.com/..."` | + + + ### Set Tags 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"]; @@ -128,12 +210,31 @@ let groupsRequest: CometChat.GroupsRequest = + +**On Success** — `fetchNext()` with tags filter returns groups matching the specified tags: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"group_1748264644578"` | +| `name` | string | Display name of the group | `"Password123NameChangedAgain"` | +| `type` | string | Group type (public, private, password) | `"password"` | +| `owner` | string | UID of the group owner | `"123456"` | +| `membersCount` | number | Total number of members in the group | `2` | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | +| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | +| `conversationId` | string | Conversation ID for this group | `"group_group_1748264644578"` | +| `createdAt` | number | Unix timestamp when group was created | `1748264644` | +| `updatedAt` | number | Unix timestamp of last update | `1768888876` | +| `updatedBy` | string | UID of user who last updated the group | `"123456"` | + + + ### With Tags 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() @@ -155,6 +256,25 @@ let groupsRequest: CometChat.GroupsRequest = + +**On Success** — `fetchNext()` with `withTags(true)` returns groups including the `tags` field: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"courses"` | +| `name` | string | Display name of the group | `"Courses"` | +| `type` | string | Group type (public, private, password) | `"public"` | +| `owner` | string | UID of the group owner | `"app_system"` | +| `membersCount` | number | Total number of members in the group | `4` | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | +| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | +| `tags` | array | Tags associated with the group | `["courses"]` | +| `conversationId` | string | Conversation ID for this group | `"group_courses"` | +| `createdAt` | number | Unix timestamp when group was created | `1764919309` | +| `updatedAt` | number | Unix timestamp of last update | `1764929127` | + + + Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the `GroupsRequest` class. Once you have the object of the `GroupsRequest` class, you need to call the `fetchNext()` method. Calling this method will return a list of `Group` objects containing n number of groups where n is the limit set in the builder class. @@ -162,7 +282,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() @@ -201,6 +321,11 @@ groupsRequest.fetchNext().then( + +**On Success** — `fetchNext()` returns an array of `Group` objects. See the filter-specific Response accordions above for field details based on your query configuration. + + + ## Retrieve Particular Group Details *In other words, as a logged-in user, how do I retrieve information for a specific group?* @@ -208,7 +333,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( @@ -244,6 +369,24 @@ CometChat.getGroup(GUID).then( | --------- | ------------------------------------------------------------ | | `GUID` | The GUID of the group for whom the details are to be fetched | + +**On Success** — `getGroup()` returns a `Group` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `guid` | string | Unique identifier of the group | `"007007"` | +| `name` | string | Display name of the group | `"Bond"` | +| `type` | string | Group type (public, private, password) | `"public"` | +| `owner` | string | UID of the group owner | `"user-b"` | +| `membersCount` | number | Total number of members in the group | `5` | +| `hasJoined` | boolean | Whether the logged-in user has joined this group | `false` | +| `isBanned` | boolean | Whether the logged-in user is banned from this group | `false` | +| `conversationId` | string | Conversation ID for this group | `"group_007007"` | +| `createdAt` | number | Unix timestamp when group was created | `1760001806` | +| `updatedAt` | number | Unix timestamp of last update | `1768398330` | + + + It returns `Group` object containing the details of the group. ## Get online group member count @@ -251,7 +394,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( @@ -283,4 +426,62 @@ CometChat.getOnlineGroupMemberCount(guids).then( + +**On Success** — `getOnlineGroupMemberCount()` returns an object with GUID as key and online count as value: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `[GUID]` | number | Online member count for the specified group | `0` | + +Example: `{"tg1": 2}` + + + 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..1dc1683e6 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,285 +41,413 @@ 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", -}; + + ```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); + ``` + + -textMessage.setMetadata(metadata); -``` +### Add Tags - +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. - -```typescript -let metadata: Object = { - latitude: "50.6192171633316", - longitude: "-72.68182268750002", -}; + + + ```javascript + let tags = ["starredMessage"]; + + textMessage.setTags(tags); + ``` + + + ```typescript + let tags: Array = ["starredMessage"]; + + textMessage.setTags(tags); + ``` + + -textMessage.setMetadata(metadata); -``` +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); + } + ); + ``` + -### Add Tags +The `TextMessage` class constructor takes the following parameters: -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. +| Parameter | Description | Required | +| ---------------- | ------------------------------------------------------------------------------------------- | -------- | +| **receiverID** | `UID` of the user or `GUID` of the group receiving the message | YES | +| **messageText** | The text message | YES | +| **receiverType** | The type of the receiver- `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | YES | - - -```javascript -let tags = ["starredMessage"]; +When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. -textMessage.setTags(tags); -``` + +**On Success** — Returns a TextMessage object: + + + +**TextMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25182"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `text` | string | Message text content | `"Hello world!"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771320772` | +| `updatedAt` | number | Unix timestamp of last update | `1771320772` | +| `sender` | object | Sender user details | [See below ↓](#send-text-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-text-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-text-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | +| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - +--- - -```typescript -let tags: Array = ["starredMessage"]; + -textMessage.setTags(tags); -``` +**`sender` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User 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); - } -); -``` +**`receiver` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | - -```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); - } -); -``` +**`data` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello world!"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_13-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-text-data-entities-object) | +| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | +| `moderation` | object | Moderation status | [See below ↓](#send-text-data-moderation-object) | - +--- -The `TextMessage` class constructor takes the following parameters: + -| Parameter | Description | Required | -| ---------------- | ------------------------------------------------------------------------------------------- | -------- | -| **receiverID** | `UID` of the user or `GUID` of the group receiving the message | YES | -| **messageText** | The text message | YES | -| **receiverType** | The type of the receiver- `CometChat.RECEIVER_TYPE.USER` or `CometChat.RECEIVER_TYPE.GROUP` | YES | +**`data.entities` Object:** -When a text message is sent successfully, the response will include a `TextMessage` object which includes all information related to the sent message. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-text-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-text-data-entities-receiver-object) | -### 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); -``` +**`data.entities.sender` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#send-text-data-entities-sender-entity-object) | - -```typescript -textMessage.setQuotedMessageId(10); -``` +--- - + - +**`data.entities.sender.entity` Object:** -Once the text message object is ready, you need to use the `sendMessage()` method to send the text message to the recipient. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320632` | +| `tags` | array | User tags | `[]` | - - -```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); - } -); -``` +**`data.entities.receiver` Object:** - - - -```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); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#send-text-data-entities-receiver-entity-object) | - - - -```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); - } -); -``` +--- - + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771320647` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.moderation` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `status` | string | Moderation status | `"pending"` | + + + +### 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); + } + ); + ``` + 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 +455,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 +466,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 +514,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 +568,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 +668,475 @@ 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: + +**On Success** — Returns a MediaMessage object: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25189"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771323061` | +| `updatedAt` | number | Unix timestamp of last update | `1771323061` | +| `sender` | object | Sender user details | [See below ↓](#send-media-file-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-media-file-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-media-file-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | - - -```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); +**`sender` Object:** -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage) => { - console.log("message", mediaMessage); - }, - (error) => { - console.log("error in sending message", error); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | - +--- - -```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); +**`receiver` Object:** -mediaMessage.setAttachment(attachment); +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | -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 - ); - -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); +**`data` Object:** -mediaMessage.setAttachment(attachment); +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | URL to the uploaded media file | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | Media attachments | [See below ↓](#send-media-file-data-attachments-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-media-file-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "pending"}` | -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 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); +**`data.attachments` Array (per item):** -mediaMessage.setAttachment(attachment); +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | URL to the attachment | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | +| `name` | string | File name | `"1770616246_260562078_3832605b5c8a337ac672b0c60933d208.png"` | +| `mimeType` | string | MIME type | `"image/png"` | +| `extension` | string | File extension | `"png"` | +| `size` | number | File size in bytes | `2295572` | -CometChat.sendMediaMessage(mediaMessage).then( - (mediaMessage: CometChat.MediaMessage) => { - console.log("message", mediaMessage); - }, - (error: CometChat.CometChatException) => { - console.log("error in sending message", error); - } -); -``` +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-file-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-file-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#send-media-file-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | +| `tags` | array | User tags | `[]` | + +--- + + - +**`data.entities.receiver` Object:** +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#send-media-file-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + + + +### 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); + }, + (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 + ); + + 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 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); + } + ); + ``` + When a media message is sent successfully, the response will include a `MediaMessage` object which includes all information related to the sent message. + +**On Success** — Returns a MediaMessage object: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25189"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771323061` | +| `updatedAt` | number | Unix timestamp of last update | `1771323061` | +| `sender` | object | Sender user details | [See below ↓](#send-media-url-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-media-url-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-media-url-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | URL to the media file | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | Media attachments | [See below ↓](#send-media-url-data-attachments-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-media-url-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "pending"}` | + +--- + + + +**`data.attachments` Array (per item):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | URL to the attachment | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | +| `name` | string | File name | `"mario"` | +| `mimeType` | string | MIME type | `"image/png"` | +| `extension` | string | File extension | `"png"` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-media-url-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-media-url-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#send-media-url-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#send-media-url-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + + + ## 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,348 +1189,489 @@ 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: +### 2. By Providing the URL of 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", -}; + + ```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 + ); -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); + } + ); + ``` + + + ```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 attachments = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); + 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); + } + ); + ``` + + -mediaMessage.setAttachments(attachments); +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) => { - console.log("message", mediaMessage); - }, - (error) => { - console.log("error in sending message", error); - } -); -``` +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 Success** — Returns a MediaMessage object with multiple attachments: + + + +**MediaMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25189"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771323061` | +| `updatedAt` | number | Unix timestamp of last update | `1771323061` | +| `sender` | object | Sender user details | [See below ↓](#send-multi-attach-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-multi-attach-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-multi-attach-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | - -```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)); +**`sender` Object:** -mediaMessage.setAttachments(attachments); +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | -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 - ); - -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", -}; +**`receiver` Object:** -let attachments: Array = []; -attachments.push(new CometChat.Attachment(attachment1)); -attachments.push(new CometChat.Attachment(attachment2)); +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | -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 attachment1: Object = { - name: "mario", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/mario/mario_PNG125.png", -}; +**`data` Object:** -let attachment2: Object = { - name: "jaguar", - extension: "png", - mimeType: "image/png", - url: "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png", -}; +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `type` | string | Media type | `"image"` | +| `category` | string | Message category | `"message"` | +| `url` | string | URL to the primary media file | `"https://data-in.cometchat.io/.../c35f9734fc20947b7456bbea68126f99.png"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `attachments` | array | Media attachments | [See below ↓](#send-multi-attach-data-attachments-array) | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-multi-attach-data-entities-object) | +| `moderation` | object | Moderation status | `{"status": "pending"}` | -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); - } -); -``` +**`data.attachments` Array (per item):** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `url` | string | URL to the attachment | `"https://pngimg.com/uploads/mario/mario_PNG125.png"` | +| `name` | string | File name | `"mario"` | +| `mimeType` | string | MIME type | `"image/png"` | +| `extension` | string | File extension | `"png"` | -
+Example with multiple attachments: +- Attachment 1: `{"name": "mario", "extension": "png", "mimeType": "image/png", "url": "https://pngimg.com/uploads/mario/mario_PNG125.png"}` +- Attachment 2: `{"name": "jaguar", "extension": "png", "mimeType": "image/png", "url": "https://pngimg.com/uploads/jaguar/jaguar_PNG20759.png"}` -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. + -## Custom Message +**`data.entities` Object:** -*In other words, as a sender, how do I send a custom message like location coordinates?* +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-multi-attach-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-multi-attach-data-entities-receiver-object) | -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. +**`data.entities.sender` Object:** - - -```javascript -let customMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#send-multi-attach-data-entities-sender-entity-object) | - +--- - -```javascript -let customMessage: CometChat.CustomMessage = new CometChat.CustomMessage( - receiverID, - receiverType, - customType, - customData -); -``` + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323060` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#send-multi-attach-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | - + +## Custom Message + +*In other words, as a sender, how do I send a custom message like location coordinates?* + +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. + + + + ```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,399 +1680,560 @@ 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"]; + + ```javascript + let tags = ["starredMessage"]; + + customMessage.setTags(tags); + ``` + + + ```typescript + let tags: Array = ["starredMessage"]; + + customMessage.setTags(tags); + ``` + + -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 = "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 + ); - -```typescript -let tags: Array = ["starredMessage"]; + 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.setTags(tags); -``` + 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. -
+On success, you will receive an object of the `CustomMessage` class. -Once the object of `CustomMessage` class is ready you can send the custom message using the `sendCustomMessage()` method. + +**On Success** — Returns a CustomMessage object: + + + +**CustomMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25190"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `type` | string | Custom message type | `"location"` | +| `category` | string | Message category | `"custom"` | +| `receiverId` | string | UID of the receiver | `"cometchat-uid-3"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sentAt` | number | Unix timestamp when sent | `1771323234` | +| `updatedAt` | number | Unix timestamp of last update | `1771323234` | +| `customData` | object | Custom payload data | [See below ↓](#send-custom-customdata-object) | +| `sender` | object | Sender user details | [See below ↓](#send-custom-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-custom-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-custom-data-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether logged-in user is mentioned | `false` | +| `metadata` | object | Custom metadata | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | - - -```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); - } -); -``` +**`customData` Object:** - - - -```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); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `latitude` | string | Latitude coordinate | `"50.6192171633316"` | +| `longitude` | string | Longitude coordinate | `"-72.68182268750002"` | - - - -```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 - ); - -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); - } -); -``` +--- - + - +**`sender` Object:** -The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the sender | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | +| `hasBlockedMe` | boolean | Whether sender has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked sender | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | -On success, you will receive an object of the `CustomMessage` class. +--- -### Update Conversation + -*How can I decide whether the custom message should update the last message of a conversation?* +**`receiver` Object:** -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. +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier of the receiver | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `hasBlockedMe` | boolean | Whether receiver has blocked logged-in user | `false` | +| `blockedByMe` | boolean | Whether logged-in user has blocked receiver | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | - - -```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); - } -); -``` +**`data` Object:** - - - -```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); - } -); -``` +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Fallback text | `"Sent a custom message"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `customData` | object | Custom payload data | `{"latitude": "50.6192171633316", "longitude": "-72.68182268750002"}` | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-custom-data-entities-object) | +| `metadata` | object | Injected metadata from extensions | `{"@injected": {"extensions": {"link-preview": {"links": []}}}}` | +| `moderation` | object | Moderation status | `{"status": "pending"}` | - - - -```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); - } -); -``` +--- - + - +**`data.entities` Object:** -### Custom Notification Body +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-custom-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-custom-data-entities-receiver-object) | -*How can i customise the notification body of 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. + - - -```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); - } -); -``` +**`data.entities.sender` Object:** - +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Sender user details | [See below ↓](#send-custom-data-entities-sender-entity-object) | - -```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); - } -); -``` +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-2"` | +| `name` | string | Display name | `"George Alan"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"` | +| `status` | string | Online status | `"online"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771323089` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | Receiver user details | [See below ↓](#send-custom-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | Unique identifier | `"cometchat-uid-3"` | +| `name` | string | Display name | `"Nancy Grace"` | +| `avatar` | string | URL to avatar image | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"` | +| `status` | string | Online status | `"offline"` | +| `role` | string | User role | `"default"` | +| `lastActiveAt` | number | Unix timestamp of last activity | `1771322968` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-2_user_cometchat-uid-3"` | +| `tags` | array | User tags | `[]` | + + + +### Update Conversation - +*How can I decide whether the custom message should update the last message of a conversation?* + +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); + } + ); + ``` + - +### Custom Notification Body + +*How can I customize the notification body of a custom message?* -It is also possible to send interactive messages from CometChat, to know more [click here](/sdk/react-native/interactive-messages) +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 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 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..4e42fc67b 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,262 @@ 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 + ``` + + - + +**Android only:** `@react-native-async-storage/async-storage` v3 ships a local Maven artifact. Add this to your `android/build.gradle` or the Android build will fail. + + + + ```gradle + allprojects { + repositories { + google() + mavenCentral() + maven { + url = uri(project(":react-native-async-storage_async-storage").file("local_repo")) + } + } + } + ``` + ## 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. + + - - -#### Android: - -Goto `./android` folder and open **project level** `build.gradle` file and add all repository URLs in the `repositories` block under the `allprojects` section. - - - -```java -allprojects { -repositories { - maven { - url "https://dl.cloudsmith.io/public/cometchat/cometchat-pro-android/maven/" - } -} -} -``` - - +## Initialize CometChat - +The `init()` method initializes the settings required for CometChat. The `init()` method takes the below parameters: -Also in the same file in `buildscript` section in `ext` block make sure you have set **minSdkVersion** to **24.** +| Parameter | Description | +| ------------ | ---------------------------------------------------------------------------------------------------------- | +| `appID` | Your CometChat App ID | +| `appSettings`| An object of the `AppSettings` class created using the `AppSettingsBuilder` class. The region is mandatory. | - - -```gradle -buildscript { - ext { - buildToolsVersion = "29.0.2" - minSdkVersion = 24 - compileSdkVersion = 29 - targetSdkVersion = 29 - } -} -``` - - - - +The `AppSettings` class allows you to configure the following settings: -#### iOS: +| 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 | -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.` +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. - -``` -platform :ios, '11.0' -``` - - - + + ```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); + } + ); + ``` + -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. + +Make sure you replace the `APP_ID` with your CometChat **App ID** and `REGION` with your **App Region** in the above code. + - - -```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); - } -); + +**On Success** — `init()` returns `true` and logs: ``` - - - - -```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); - } -); +Initialization completed successfully ``` - - - - -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. | +**On Failure** — Returns a CometChatException object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `code` | string | Error code | `"ERR_INVALID_APP_ID"` | +| `name` | string | Error name | `"Invalid App ID"` | +| `message` | string | Error description | `"The App ID provided is incorrect. Please verify your App ID from the CometChat Dashboard."` | +| `details` | object | Additional error details | `{}` | + + + + + + - 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..e4bc97276 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..e3f99044d 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,245 @@ 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`: + + + +**Message Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25293"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello thread!"` | +| `sentAt` | number | Unix timestamp when sent | `1771839799` | +| `updatedAt` | number | Unix timestamp when updated | `1771839799` | +| `parentMessageId` | string | ID of the parent message this reply belongs to | `"25291"` | +| `sender` | object | Sender user details | [See below ↓](#send-thread-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#send-thread-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#send-thread-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#send-thread-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771839550` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771839549` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello thread!"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#send-thread-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#send-thread-data-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "pending"}` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#send-thread-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#send-thread-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#send-thread-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771839550` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#send-thread-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771839549` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#send-thread-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#send-thread-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#send-thread-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#send-thread-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#send-thread-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#send-thread-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted 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 +391,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 +425,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 +444,469 @@ messagesRequest.fetchPrevious().then( + +**On Success** — `fetchPrevious()` returns an array of messages belonging to the thread: + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25293"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello thread!"` | +| `sentAt` | number | Unix timestamp when sent | `1771839799` | +| `updatedAt` | number | Unix timestamp when updated | `1771839799` | +| `parentMessageId` | string | ID of the parent message this reply belongs to | `"25291"` | +| `sender` | object | Sender user details | [See below ↓](#fetch-thread-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#fetch-thread-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#fetch-thread-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#fetch-thread-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771839550` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771839549` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello thread!"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#fetch-thread-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#fetch-thread-data-metadata-object) | +| `moderation` | object | Moderation status | `{"status": "approved"}` | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#fetch-thread-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#fetch-thread-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#fetch-thread-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771839550` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#fetch-thread-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771839549` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#fetch-thread-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#fetch-thread-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#fetch-thread-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#fetch-thread-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#fetch-thread-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#fetch-thread-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + + ## 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`): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25291"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello"` | +| `sentAt` | number | Unix timestamp when sent | `1771831336` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | +| `readAt` | number | Unix timestamp when read | `1771832977` | +| `updatedAt` | number | Unix timestamp when updated | `1771832977` | +| `replyCount` | number | Number of replies to this message | `1` | +| `sender` | object | Sender user details | [See below ↓](#default-behavior-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#default-behavior-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#default-behavior-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#default-behavior-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +Thread replies in the same response will have a `parentMessageId` field linking them to their parent message. + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#default-behavior-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#default-behavior-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#default-behavior-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#default-behavior-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#default-behavior-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#default-behavior-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#default-behavior-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#default-behavior-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#default-behavior-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#default-behavior-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#default-behavior-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#default-behavior-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + - + ```javascript let UID = "UID"; let limit = 30; @@ -205,7 +927,7 @@ messagesRequest.fetchPrevious().then( - + ```javascript let GUID = "GUID"; let limit = 30; @@ -226,7 +948,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let UID: string = "UID", limit: number = 30, @@ -247,7 +969,7 @@ messagesRequest.fetchPrevious().then( - + ```typescript let GUID: string = "GUID", limit: number = 30, @@ -270,4 +992,269 @@ 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): + + + +**Message Object (per item in array):** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `id` | string | Unique message identifier | `"25291"` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `receiverId` | string | Receiver's UID | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `type` | string | Message type | `"text"` | +| `category` | string | Message category | `"message"` | +| `text` | string | Message text content | `"Hello"` | +| `sentAt` | number | Unix timestamp when sent | `1771831336` | +| `deliveredAt` | number | Unix timestamp when delivered | `1771832977` | +| `readAt` | number | Unix timestamp when read | `1771832977` | +| `updatedAt` | number | Unix timestamp when updated | `1771832977` | +| `replyCount` | number | Number of replies to this message | `1` | +| `sender` | object | Sender user details | [See below ↓](#hide-replies-sender-object) | +| `receiver` | object | Receiver user details | [See below ↓](#hide-replies-receiver-object) | +| `data` | object | Additional message data | [See below ↓](#hide-replies-data-object) | +| `metadata` | object | Message metadata | [See below ↓](#hide-replies-metadata-object) | +| `reactions` | array | Message reactions | `[]` | +| `mentionedUsers` | array | Users mentioned in message | `[]` | +| `mentionedMe` | boolean | Whether current user is mentioned | `false` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `text` | string | Message text | `"Hello"` | +| `resource` | string | SDK resource identifier | `"REACT_NATIVE-4_0_14-..."` | +| `entities` | object | Sender and receiver entities | [See below ↓](#hide-replies-data-entities-object) | +| `metadata` | object | Injected metadata | [See below ↓](#hide-replies-data-metadata-object) | + +--- + + + +**`data.entities` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `sender` | object | Sender entity wrapper | [See below ↓](#hide-replies-data-entities-sender-object) | +| `receiver` | object | Receiver entity wrapper | [See below ↓](#hide-replies-data-entities-receiver-object) | + +--- + + + +**`data.entities.sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#hide-replies-data-entities-sender-entity-object) | + +--- + + + +**`data.entities.sender.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-7"` | +| `name` | string | User's display name | `"Henry Marino"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-7.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829868` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.entities.receiver` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `entityType` | string | Type of entity | `"user"` | +| `entity` | object | User entity details | [See below ↓](#hide-replies-data-entities-receiver-entity-object) | + +--- + + + +**`data.entities.receiver.entity` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | User's avatar URL | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `role` | string | User's role | `"default"` | +| `status` | string | User's online status | `"online"` | +| `lastActiveAt` | number | Last active timestamp | `1771829859` | +| `conversationId` | string | Conversation identifier | `"cometchat-uid-6_user_cometchat-uid-7"` | +| `tags` | array | User tags | `[]` | + +--- + + + +**`data.metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#hide-replies-data-metadata-injected-object) | + +--- + + + +**`data.metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#hide-replies-data-metadata-extensions-object) | + +--- + + + +**`data.metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#hide-replies-data-metadata-linkpreview-object) | + +--- + + + +**`data.metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + +--- + + + +**`metadata` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `@injected` | object | Injected extensions data | [See below ↓](#hide-replies-metadata-injected-object) | + +--- + + + +**`metadata.@injected` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `extensions` | object | Extensions data | [See below ↓](#hide-replies-metadata-extensions-object) | + +--- + + + +**`metadata.@injected.extensions` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `link-preview` | object | Link preview extension | [See below ↓](#hide-replies-metadata-linkpreview-object) | + +--- + + + +**`metadata.@injected.extensions.link-preview` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `links` | array | Extracted links | `[]` | + + + +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..0ce97642a 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,45 @@ CometChat.transferGroupOwnership(GUID, UID).then( + + +**On Success** — `transferGroupOwnership()` returns a success message: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `message` | string | Success confirmation message | `"Ownership transferred to user cometchat-uid-2 for the group with guid group_with_members_1772429132099."` | + + + + + +- 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..82633a423 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,31 @@ CometChat.sendTransientMessage(transientMessage); + +**On Success** — `sendTransientMessage()` does not return a value, but the transient message object sent looks like: + + + +**TransientMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `data` | object | Custom data payload | [See below ↓](#send-transient-data-object) | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `LIVE_REACTION` | string | Live reaction type | `"heart"` | + + + ## Real-time Transient Messages *In other words, as a recipient, how do I know when someone sends a transient message?* @@ -68,7 +108,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 +142,54 @@ CometChat.addMessageListener( + +**On Event** — `onTransientMessageReceived` returns the transient message object with sender info: + + + +**TransientMessage Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `data` | object | Custom data payload | [See below ↓](#receive-transient-data-object) | +| `sender` | object | User who sent the transient message | [See below ↓](#receive-transient-sender-object) | + +--- + + + +**`data` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `LIVE_REACTION` | string | Live reaction type | `"heart"` | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User 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 +198,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..577a593bf 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: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"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: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-6"` | +| `receiverType` | string | Type of receiver | `"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,112 @@ CometChat.addMessageListener( + +**onTypingStarted** — received when a user starts typing: + + + +**TypingIndicator Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sender` | object | User who is typing | [See below ↓](#typing-started-sender-object) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User tags | `[]` | + +--- + +**onTypingEnded** — received when a user stops typing: + + + +**TypingIndicator Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `receiverId` | string | Receiver's unique identifier | `"cometchat-uid-7"` | +| `receiverType` | string | Type of receiver | `"user"` | +| `sender` | object | User who stopped typing | [See below ↓](#typing-ended-sender-object) | + +--- + + + +**`sender` Object:** + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `uid` | string | User's unique identifier | `"cometchat-uid-6"` | +| `name` | string | User's display name | `"Ronald Jerry"` | +| `avatar` | string | URL to user's avatar | `"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-6.webp"` | +| `status` | string | User's online status | `"online"` | +| `role` | string | User's role | `"default"` | +| `hasBlockedMe` | boolean | Whether user has blocked current user | `false` | +| `blockedByMe` | boolean | Whether current user blocked this user | `false` | +| `deactivatedAt` | number | Deactivation timestamp (0 if active) | `0` | +| `tags` | array | User 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..35ec4ed0e 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"; @@ -58,4 +70,67 @@ 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. + +**On Success** — `updateGroup()` returns the updated `Group` object: + +| Parameter | Type | Description | Sample Value | +|-----------|------|-------------|--------------| +| `hasJoined` | boolean | Whether the logged-in user has joined the group | `true` | +| `membersCount` | number | Total number of members in the group | `2` | +| `isBanned` | boolean | Whether the logged-in user is banned from the group | `false` | +| `guid` | string | Unique identifier of the group | `"group_1772427551785"` | +| `name` | string | Updated name of the group | `"Comet Group Updated"` | +| `type` | string | Type of the group (public, private, password) | `"public"` | +| `scope` | string | Scope of the logged-in user in the group | `"admin"` | +| `joinedAt` | number | Unix timestamp when the user joined | `1772427556` | +| `conversationId` | string | Conversation ID for the group | `"group_group_1772427551785"` | +| `createdAt` | number | Unix timestamp when the group was created | `1772427556` | +| `owner` | string | UID of the group owner | `"cometchat-uid-6"` | +| `updatedAt` | number | Unix timestamp when the group was last updated | `1772427918` | +| `updatedBy` | string | UID of the user who updated the group | `"cometchat-uid-6"` | +| `onlineMembersCount` | number | Number of online members in the group | `2` | + + + 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 diff --git a/ui-kit/flutter/property-changes.mdx b/ui-kit/flutter/property-changes.mdx deleted file mode 100644 index c38585b34..000000000 --- a/ui-kit/flutter/property-changes.mdx +++ /dev/null @@ -1,455 +0,0 @@ ---- -title: "Property Changes" ---- - -## Conversations - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| scrollController | ScrollController? | Controller to handle scrolling behavior in the conversations list. | -| datePadding | EdgeInsets? | Provides padding for the date component. | -| dateHeight | double? | Provides height for the date component. | -| dateBackgroundIsTransparent | bool? | Controls the background transparency of the date component. | -| dateWidth | double? | Provides width for the date component. | -| badgeWidth | double? | Provides width for the badge component. | -| badgeHeight | double? | Provides height for the badge component. | -| badgePadding | EdgeInsetsGeometry? | Provides padding for the badge component. | -| statusIndicatorWidth | double? | Provides width for the status indicator. | -| statusIndicatorHeight | double? | Provides height for the status indicator. | -| statusIndicatorBorderRadius | BorderRadiusGeometry? | Provides border radius for the status indicator. | -| avatarMargin | EdgeInsetsGeometry? | Provides margin for the avatar component. | -| avatarPadding | EdgeInsetsGeometry? | Provides padding for the avatar component. | -| avatarWidth | double? | Provides width for the avatar component. | -| avatarHeight | double? | Provides height for the avatar component. | -| deleteConversationOptionVisibility | bool | Controls visibility of delete conversation option (default: true). | -| groupTypeVisibility | bool | Controls visibility of group type icon (default: true). | -| setOptions | Function? | Sets custom options for conversation long press actions. | -| addOptions | Function? | Adds additional options to conversation long press actions. | -| loadingStateView | WidgetBuilder? | Custom widget for loading state view. | -| leadingView | Function? | Custom widget for leading view of conversation items. | -| titleView | Function? | Custom widget for title view of conversation items. | -| controllerTag | String? | Tag for controller management. | -| onLoad | OnLoad< Conversation >? | Callback when conversations are loading. | -| onEmpty | OnEmpty? | Callback when conversation list is empty. | -| submitIcon | Widget? | Custom submit icon for selection mode. | -| dateTimeFormatterCallback | DateTimeFormatterCallback? | Callback for custom date and time formatting. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| conversationsStyle | conversationsStyle | ConversationsStyle → CometChatConversationsStyle | Style configuration (type changed from ConversationsStyle to CometChatConversationsStyle). | -| tailView | trailingView | Function? | Custom widget for trailing view of conversation items (renamed from tailView to trailingView). | -| disableUsersPresence | usersStatusVisibility | bool | Controls user status visibility (inverted logic: disableUsersPresence=false becomes usersStatusVisibility=true). | -| hideReceipt/disableReceipt | receiptsVisibility | bool | Controls receipt visibility (inverted logic: hideReceipt=false becomes receiptsVisibility=true). | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the conversations component. | -| errorStateText | String? | Custom text for error state display. | -| emptyStateText | String? | Custom text for empty state display. | -| stateCallBack | Function? | Callback for state changes in the conversations component. | -| loadingStateText | String? | Custom text for loading state display. | -| options | Function? | Options configuration for conversation items. | -| avatarStyle | AvatarStyle? | Style configuration for avatar components. | -| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicators. | -| badgeStyle | BadgeStyle? | Style configuration for badge components. | -| receiptStyle | ReceiptStyle? | Style configuration for receipt indicators. | -| hideSeparator | bool | Controls visibility of separators between conversation items. | -| dateStyle | DateStyle? | Style configuration for date components. | -| disableTyping | bool? | Controls typing indicator functionality. | -| deleteConversationDialogStyle | ConfirmDialogStyle? | Style configuration for delete conversation confirmation dialog. | -| disableMentions | bool? | Controls mention functionality in conversations. | - -## Users - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| scrollController | ScrollController? | Sets controller for scrolling behavior in the users list. | -| height | double? | Provides height to the widget. | -| width | double? | Provides width to the widget. | -| stickyHeaderVisibility | bool | Hide alphabets used to separate users (default: false). | -| searchKeyword | String? | Used to set searchKeyword to fetch initial list with. | -| onLoad | OnLoad< User >? | Callback triggered when list is fetched and loaded. | -| onEmpty | OnEmpty? | Callback triggered when the list is empty. | -| setOptions | Function? | Sets list of actions available on the long press of list item. | -| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | -| trailingView | Widget? Function(BuildContext, User)? | Custom widget for trailing view of each user item. | -| leadingView | Widget? Function(BuildContext, User)? | Custom widget for leading view of each user item. | -| titleView | Widget? Function(BuildContext, User)? | Custom widget for title view of each user item. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| controller | scrollController | ScrollController? | Scroll controller for the list (renamed from controller to scrollController). | -| disableUsersPresence | usersStatusVisibility | bool → bool | Controls user status visibility (inverted logic: disableUsersPresence=false becomes usersStatusVisibility=true). | -| hideSectionSeparator | stickyHeaderVisibility | bool → bool | Controls section separator visibility (inverted logic: hideSectionSeparator=false becomes stickyHeaderVisibility=true). | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the users component. | -| errorStateText | String? | Custom text for error state display. | -| emptyStateText | String? | Custom text for empty state display. | -| stateCallBack | Function? | Callback to access controller functions from parent. | -| hideError | bool? | Toggle visibility of error dialog. | -| listItemStyle | ListItemStyle? | Style configuration for individual list items. | -| options | Function? | Options configuration for user items. | -| avatarStyle | AvatarStyle? | Style configuration for avatar components. | -| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicators. | -| hideSeparator | bool? | Toggle visibility of separator between items. | -| hideSectionSeparator | bool? | Toggle visibility of section separators. | -| selectionIcon | Widget? | Custom selection icon widget. | - -## Groups - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| scrollController | ScrollController? | Sets controller for scrolling behavior in the groups list. | -| height | double? | Provides height to the widget. | -| width | double? | Provides width to the widget. | -| searchKeyword | String? | Used to set searchKeyword to fetch initial list with. | -| onLoad | OnLoad< Group >? | Callback triggered when list is fetched and loaded. | -| onEmpty | OnEmpty? | Callback triggered when the list is empty. | -| groupTypeVisibility | bool | Hide the group type icon which is visible on the group icon (default: true). | -| setOptions | Function? | Sets list of actions available on the long press of list item. | -| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | -| trailingView | Widget? Function(BuildContext, Group)? | Custom widget for trailing view of each group item. | -| leadingView | Widget? Function(BuildContext, Group)? | Custom widget for leading view of each group item. | -| titleView | Widget? Function(BuildContext, Group)? | Custom widget for title view of each group item. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| controller | scrollController | ScrollController? | Scroll controller for the list (renamed from controller to scrollController). | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the groups component. | -| errorStateText | String? | Custom text for error state display. | -| emptyStateText | String? | Custom text for empty state display. | -| listItemStyle | ListItemStyle? | Style configuration for individual list items. | -| options | Function? | Options configuration for group items. | -| avatarStyle | AvatarStyle? | Style configuration for avatar components. | -| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicators. | -| hideSeparator | bool | Toggle visibility of separator between items. | -| selectionIcon | Widget? | Custom selection icon widget. | - -## Group Members - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| height | double? | Provides height to the widget. | -| width | double? | Provides width to the widget. | -| controllerTag | String? | Tag to access the widget's GetXController. | -| searchKeyword | String? | Used to set searchKeyword to fetch initial list with. | -| onLoad | OnLoad< GroupMember >? | Callback triggered when list is fetched and loaded. | -| onEmpty | OnEmpty? | Callback triggered when the list is empty. | -| leadingView | Widget? Function(BuildContext, GroupMember)? | Custom widget for leading view of each group member item. | -| titleView | Widget? Function(BuildContext, GroupMember)? | Custom widget for title view of each group member item. | -| usersStatusVisibility | bool | Hide status indicator of user which is visible on user avatar (default: true). | -| hideKickMemberOption | bool? | Defines whether a member can be kicked or not. | -| hideBanMemberOption | bool? | Defines whether a member can be banned or not. | -| hideScopeChangeOption | bool? | Defines whether a member's scope can be changed or not. | -| setOptions | Function? | Sets list of actions available on the long press of list item. | -| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| groupMemberStyle | style | GroupMembersStyle → CometChatGroupMembersStyle | Style configuration (type changed from GroupMembersStyle to CometChatGroupMembersStyle). | -| tailView | trailingView | Function → Function | Custom widget for trailing view (renamed from tailView to trailingView). | -| disableUsersPresence | usersStatusVisibility | bool → bool | Controls user status visibility (inverted logic: disableUsersPresence=false becomes usersStatusVisibility=true). | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the group members component. | -| title | String? | Sets title for the list. | -| errorStateText | String? | Text to be displayed when error occurs. | -| emptyStateText | String? | Text to be displayed when the list is empty. | -| listItemStyle | ListItemStyle? | Style configuration for individual list items. | -| avatarStyle | AvatarStyle? | Style configuration for avatar components. | -| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicator. | -| groupScopeStyle | GroupScopeStyle? | Styling properties for group scope (integrated into main style). | - -## Message Header - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| trailingView | List< Widget >? Function(User?, Group?, BuildContext)? | Custom widgets for trailing view in the message header. | -| height | double? | Sets height for the message header component. | -| padding | EdgeInsetsGeometry? | Sets padding for the message header component. | -| hideVideoCallButton | bool? | Controls visibility of video call button in the header. | -| hideVoiceCallButton | bool? | Controls visibility of voice call button in the header. | -| titleView | Widget? Function(Group?, User?, BuildContext)? | Custom widget for title view in the message header. | -| leadingStateView | Widget? Function(Group?, User?, BuildContext)? | Custom widget for leading state view in the message header. | -| auxiliaryButtonView | Widget? Function(Group?, User?, BuildContext)? | Custom widget for auxiliary button view in the message header. | -| usersStatusVisibility | bool | Controls visibility of user status indicator (default: true). | -| dateTimeFormatterCallback | DateTimeFormatterCallback? | Callback for custom date and time formatting. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| hideBackButton | showBackButton | bool → bool | Controls back button visibility (inverted logic: hideBackButton=false becomes showBackButton=true). | -| disableUserPresence | usersStatusVisibility | bool → bool | Controls user presence visibility (inverted logic: disableUserPresence=false becomes usersStatusVisibility=true). | -| appBarOptions | trailingView | Function → Function | Custom widgets for header options (renamed from appBarOptions to trailingView). | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the message header component. | -| avatarStyle | AvatarStyle? | Style configuration for avatar in the header. | -| statusIndicatorStyle | StatusIndicatorStyle? | Style configuration for status indicator in the header. | -| privateGroupIcon | Widget? | Custom icon for private groups in the header. | -| protectedGroupIcon | Widget? | Custom icon for protected groups in the header. | -| disableTyping | bool | Controls typing indicator functionality in the header. | - -## Message List - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| style | CometChatMessageListStyle? | Sets style for message list (replaces messageListStyle). | -| receiptsVisibility | bool | Controls visibility of read receipts (default: true). | -| avatarVisibility | bool | Toggle visibility for avatar (default: true, renamed from showAvatar). | -| padding | EdgeInsetsGeometry? | Sets padding for the message list. | -| margin | EdgeInsetsGeometry? | Sets margin for the message list. | -| width | double? | Sets width for the message list. | -| height | double? | Sets height for the message list. | -| reactionsRequestBuilder | ReactionsRequestBuilder? | Used to fetch the reactions of a particular message. | -| onLoad | OnLoad< BaseMessage >? | Callback triggered when list is fetched and loaded. | -| onEmpty | OnEmpty? | Callback triggered when the list is empty. | -| onReactionClick | Function(String?, BaseMessage)? | Override the click of a reaction pill. | -| onReactionLongPress | Function(String?, BaseMessage)? | Override when user long presses on a reaction pill. | -| onReactionListItemClick | Function(String?, BaseMessage?)? | Override when a reaction list item is clicked. | -| hideStickyDate | bool | Hide the sticky date separator. | -| hideReplyInThreadOption | bool | Defines whether Reply In Thread option should be visible. | -| hideTranslateMessageOption | bool | Defines whether Translate Message option should be visible. | -| hideEditMessageOption | bool | Defines whether Edit Message option should be visible. | -| hideDeleteMessageOption | bool | Defines whether Delete Message option should be visible. | -| hideReactionOption | bool | Defines whether Reaction option should be visible. | -| hideMessagePrivatelyOption | bool | Defines whether Message Privately option should be visible. | -| hideCopyMessageOption | bool | Defines whether Copy Message option should be visible. | -| hideMessageInfoOption | bool | Defines whether Message Info option should be visible. | -| hideGroupActionMessages | bool | Defines whether action messages in groups should be visible. | -| enableConversationStarters | bool | Controls conversation starter generation in new conversations. | -| enableSmartReplies | bool | Controls smart replies generation in chat. | -| hideShareMessageOption | bool | Defines whether Share Message option should be visible. | -| smartRepliesDelayDuration | int | Milliseconds delay after which Smart Replies are triggered. | -| smartRepliesKeywords | List< String > | Keywords that trigger Smart Replies. | -| addTemplate | List< CometChatMessageTemplate >? | Add custom message templates to existing templates. | -| dateTimeFormatterCallback | DateTimeFormatterCallback? | Callback for custom date and time formatting. | -| hideModerationView | bool | Defines whether moderation view should be hidden. | -| hideDateSeparator | bool | Hide the date separator (default: false). | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| messageListStyle | style | MessageListStyle → CometChatMessageListStyle | Style configuration (type changed). | -| controller | scrollController | ScrollController? | Scroll controller for the list. | -| showAvatar | avatarVisibility | bool → bool | Toggle visibility for avatar. | -| disableReceipt/hideReceipt | receiptsVisibility | bool → bool | Controls receipt visibility (inverted logic). | -| addReactionIconTap | addMoreReactionTap | Function → Function | Callback for adding more reactions. | -| dateSeparatorPattern | dateSeparatorPattern | Function(DateTime) → Function(DateTime) | Signature clarified with parameter name. | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| hideError | bool? | Toggle visibility of error dialog. | -| theme | CometChatTheme? | Theme configuration for the message list. | -| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | -| scrollToBottomOnNewMessages | bool? | Auto-scroll to bottom on new messages. | -| newMessageIndicatorText | String? | Custom text for new message indicator. | -| timestampAlignment | TimeAlignment | Alignment for message timestamps. | -| messageInformationConfiguration | MessageInformationConfiguration? | Configuration for message information. | -| reactionListConfiguration | ReactionListConfiguration? | Configuration for reaction list. | -| reactionsConfiguration | ReactionsConfiguration? | Configuration for reactions. | -| reactionsStyle | ReactionsStyle? | Style configuration for reactions. | -| emojiKeyboardStyle | EmojiKeyboardStyle? | Style configuration for emoji keyboard. | -| disableReceipt | bool? | (Deprecated) Controls visibility of read receipts. | -| hideReceipt | bool? | Controls visibility of read receipts (replaced by receiptsVisibility). | - -## Message Composer - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| padding | EdgeInsetsGeometry? | Provides padding to the message composer. | -| messageInputPadding | EdgeInsetsGeometry? | Sets the padding to the message input field. | -| recorderStartButtonIcon | Widget? | Defines the icon of the start button for voice recording. | -| recorderPauseButtonIcon | Widget? | Defines the icon of the pause button for voice recording. | -| recorderDeleteButtonIcon | Widget? | Defines the icon of the delete button for voice recording. | -| recorderStopButtonIcon | Widget? | Defines the icon of the stop button for voice recording. | -| recorderSendButtonIcon | Widget? | Defines the icon of the send button for voice recording. | -| hideSendButton | bool? | Controls visibility of send button. | -| hideAttachmentButton | bool? | Controls visibility of attachment button. | -| hideStickersButton | bool? | Controls visibility of sticker button. | -| hideImageAttachmentOption | bool? | Controls visibility of image attachment option. | -| hideVideoAttachmentOption | bool? | Controls visibility of video attachment option. | -| hideAudioAttachmentOption | bool? | Controls visibility of audio attachment option. | -| hideFileAttachmentOption | bool? | Controls visibility of file attachment option. | -| hidePollsOption | bool? | Controls visibility of poll option. | -| hideCollaborativeDocumentOption | bool? | Controls visibility of collaborative document option. | -| hideCollaborativeWhiteboardOption | bool? | Controls visibility of collaborative whiteboard option. | -| hideTakePhotoOption | bool? | Controls visibility of take photo option. | -| sendButtonIcon | Widget? | Custom send button icon. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| hideVoiceRecording | hideVoiceRecordingButton | bool? → bool? | Renamed for clarity (hideVoiceRecording to hideVoiceRecordingButton). | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the message composer. | -| hideLiveReaction | bool | Controls live reaction functionality (feature removed). | -| liveReactionIcon | Widget? | Custom live reaction icon (feature removed). | -| liveReactionIconURL | String? | Path for live reaction icon (feature removed). | -| recordIcon | Widget? | Icon for recording start (replaced by recorderStartButtonIcon). | -| playIcon | Widget? | Icon for playing recording (integrated into recorder). | -| deleteIcon | Widget? | Icon for deleting recording (replaced by recorderDeleteButtonIcon). | -| stopIcon | Widget? | Icon for stopping recording (replaced by recorderStopButtonIcon). | -| submitIcon | Widget? | Icon for submitting recording (replaced by recorderSendButtonIcon). | -| pauseIcon | Widget? | Icon for pausing recording (replaced by recorderPauseButtonIcon). | -| mediaRecorderStyle | MediaRecorderStyle? | Style for media recorder (integrated into main style). | - -## Incoming Call - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| callSettingsBuilder | CallSettingsBuilder? | Used to set the call settings for the incoming call. | -| height | double? | Sets the height of the incoming call widget. | -| width | double? | Sets the width of the incoming call widget. | -| callIcon | Widget? | Custom call icon for the incoming call display. | -| titleView | Widget? Function(BuildContext, Call)? | Custom widget for title view in the incoming call. | -| subTitleView | Widget? Function(BuildContext, Call)? | Custom widget for subtitle view in the incoming call. | -| leadingView | Widget? Function(BuildContext, Call)? | Custom widget for leading view in the incoming call. | -| itemView | Widget? Function(BuildContext, Call)? | Custom widget for complete item view in the incoming call. | -| trailingView | Widget? Function(BuildContext, Call)? | Custom widget for trailing view in the incoming call. | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the incoming call component. | -| subtitle | String? | Custom subtitle text (replaced by subTitleView function). | -| declineButtonIconUrl | String? | Custom decline button icon URL. | -| declineButtonIconUrlPackage | String? | Package name for decline button icon. | -| cardStyle | CardStyle? | Style configuration for the card layout. | -| declineButtonStyle | ButtonStyle? | Style configuration for decline button. | -| acceptButtonIconUrl | String? | Custom accept button icon URL. | -| acceptButtonIconUrlPackage | String? | Package name for accept button icon. | -| acceptButtonStyle | ButtonStyle? | Style configuration for accept button. | -| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | -| ongoingCallConfiguration | OngoingCallConfiguration? | Configuration for ongoing call settings. | - -## Outgoing Call - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| callSettingsBuilder | CallSettingsBuilder? | Used to set the call settings for the outgoing call. | -| height | double? | Sets the height of the outgoing call widget. | -| width | double? | Sets the width of the outgoing call widget. | -| avatarView | Widget? Function(BuildContext, Call)? | Custom widget for avatar view in the outgoing call. | -| titleView | Widget? Function(BuildContext, Call)? | Custom widget for title view in the outgoing call. | -| cancelledView | Widget? Function(BuildContext, Call)? | Custom widget for cancelled/decline button view in the outgoing call. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| subtitle | subtitleView | String? → Widget? Function(BuildContext, Call)? | Subtitle changed from static text to custom widget function. | -| declineButtonIconUrl | declineButtonIcon | String? → Widget? | Decline button icon changed from URL-based to Widget-based. | -| onDecline | onCancelled | Function(BuildContext, Call)? → Function(BuildContext, Call)? | Callback renamed from onDecline to onCancelled for clarity. | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| theme | CometChatTheme? | Theme configuration for the outgoing call component. | -| subtitle | String? | Custom subtitle text (replaced by subtitleView function). | -| declineButtonText | String? | Custom decline button text. | -| declineButtonIconUrl | String? | Custom decline button icon URL (replaced by declineButtonIcon widget). | -| declineButtonIconUrlPackage | String? | Package name for decline button icon. | -| cardStyle | CardStyle? | Style configuration for the card layout. | -| buttonStyle | ButtonStyle? | Style configuration for decline button. | -| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | -| ongoingCallConfiguration | OngoingCallConfiguration? | Configuration for ongoing call settings. | - -## Call Buttons - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| callSettingsBuilder | CallSettingsBuilder Function(User?, Group?, bool?)? | Used to configure the meet settings builder for call initialization. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| hideVoiceCall | hideVoiceCallButton | bool? → bool? | Renamed for clarity (hideVoiceCall to hideVoiceCallButton). | -| hideVideoCall | hideVideoCallButton | bool? → bool? | Renamed for clarity (hideVideoCall to hideVideoCallButton). | - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| voiceCallIconText | String? | Text label for the voice call icon. | -| voiceCallIconHoverText | String? | Hover text for the voice call icon. | -| videoCallIconText | String? | Text label for the video call icon. | -| videoCallIconHoverText | String? | Hover text for the video call icon. | -| onVoiceCallClick | Function(BuildContext, User?, Group?)? | Custom callback for voice call button click. | -| onVideoCallClick | Function(BuildContext, User?, Group?)? | Custom callback for video call button click. | -| ongoingCallConfiguration | OngoingCallConfiguration? | Configuration for ongoing call settings. | - -## Call Logs - -### New Properties -| Name | Type | Description | -| ------------------------- | -------------- | ---------------------------------------------------------------------------------- | -| hideAppbar | bool | Toggle visibility for app bar (default: false). | -| appBarOptions | List< Widget >? | List of options to be visible in app bar. | -| onCallLogIconClicked | Function(CallLog)? | Callback triggered on clicking of the call log icon (audio/video icon). | -| onItemLongPress | Function(CallLog)? | Callback triggered on long pressing of the call log item. | -| onLoad | OnLoad< CallLog >? | Callback triggered when list is fetched and loaded. | -| onEmpty | OnEmpty? | Callback triggered when the list is empty. | -| setOptions | Function? | Sets list of actions available on the long press of list item. | -| addOptions | Function? | Adds into the current list of actions available on the long press of list item. | -| leadingStateView | Widget? Function(BuildContext, CallLog)? | Custom widget for leading view of each call log item. | -| titleView | Widget? Function(BuildContext, CallLog)? | Custom widget for title view of each call log item. | -| audioCallIcon | Widget? | Custom audio call icon. | -| videoCallIcon | Widget? | Custom video call icon. | -| incomingCallIcon | Widget? | Custom incoming call icon. | -| outgoingCallIcon | Widget? | Custom outgoing call icon. | -| missedCallIcon | Widget? | Custom missed call icon. | - -### Renamed Properties -| V4 Name | V5 Name | Type | Description | -| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | -| tailView | trailingView | Function → Function | Custom widget for trailing view (renamed from tailView to trailingView). | - - -### Removed Properties -| Name | Type | Description | -| ----------- | ------------ | ---------------------------------------------------------------------------------- | -| title | String? | Title of the call log list component. | -| emptyStateText | String? | Text to be displayed when the state is empty. | -| errorStateText | String? | Text to be displayed when error occurs. | -| loadingIconUrl | String? | URL to be displayed when loading. | -| avatarStyle | AvatarStyle? | Style configuration for avatar (integrated into main style). | -| theme | CometChatTheme? | Theme configuration for the call logs component. | -| hideSeparator | bool? | Toggle visibility of separator. | -| onInfoIconClick | Function(CallLog)? | Callback triggered on clicking of the info icon. | -| infoIconUrl | String? | Custom info icon URL. | -| listItemStyle | ListItemStyle? | Style configuration for individual list items. | -| incomingAudioCallIcon | String? | Custom incoming audio call icon URL (replaced by incomingCallIcon widget). | -| incomingVideoCallIcon | String? | Custom incoming video call icon URL (replaced by incomingCallIcon widget). | -| outgoingAudioCallIcon | String? | Custom outgoing audio call icon URL (replaced by outgoingCallIcon widget). | -| outgoingVideoCallIcon | String? | Custom outgoing video call icon URL (replaced by outgoingCallIcon widget). | -| missedAudioCallIcon | String? | Custom missed audio call icon URL (replaced by missedCallIcon widget). | -| missedVideoCallIcon | String? | Custom missed video call icon URL (replaced by missedCallIcon widget). | \ No newline at end of file diff --git a/ui-kit/react-native/ai-assistant-chat-history.mdx b/ui-kit/react-native/ai-assistant-chat-history.mdx index 3eca223c1..86b193335 100644 --- a/ui-kit/react-native/ai-assistant-chat-history.mdx +++ b/ui-kit/react-native/ai-assistant-chat-history.mdx @@ -1,10 +1,38 @@ --- title: "AI Assistant Chat History" +description: "Display conversation history between users and AI assistants with CometChatAIAssistantChatHistory component in React Native UI Kit." --- + +**Quick Reference for AI Agents & Developers** + +```tsx +import { CometChatAIAssistantChatHistory } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +// Basic usage with user (must have @agentic role) + console.log("Closed")} +/> + +// With common props + console.log("Selected:", message)} + onNewChatButtonClick={() => console.log("New chat")} + onClose={() => navigation.goBack()} + onError={(error) => console.log("Error:", error)} +/> +``` + +- **Message List** → [CometChatMessageList](/ui-kit/react-native/message-list) +- **AI Features** → [AI Features Overview](/ui-kit/react-native/ai-features) + + ## Overview -The `AI Assistant Chat History` component is a pre-built user interface element designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. +`CometChatAIAssistantChatHistory` is a pre-built user interface element designed to display the conversation history between users and an AI assistant within a chat application. It provides a structured and visually appealing way to present past interactions, making it easy for users to review previous messages and context. @@ -74,6 +102,9 @@ Function invoked when a chat history item is clicked, typically used to open an ```ts +import { CometChatAIAssistantChatHistory } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + { @@ -134,6 +165,9 @@ Function invoked when an error occurs during message fetching or any other opera ```ts +import { CometChatAIAssistantChatHistory } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + { @@ -147,7 +181,7 @@ Function invoked when an error occurs during message fetching or any other opera ## Customization -The `CometChatAIAssistantChatHistory` component offers a variety of customization options to tailor its appearance and functionality to better fit your application's needs. These customizations are categorized into two main areas: Style and Functionality. +To fit your app's design requirements, you can customize the appearance of the AI Assistant Chat History component. These customizations are categorized into two main areas: Style and Functionality. ### Style @@ -212,3 +246,23 @@ Below is a list of customizations along with corresponding code snippets: | user | Sets the user whose chat histories with the AI assistant need to be fetched. This is a required property for the component to function properly. | `user={userObject}` | | group | Sets the group whose chat histories with the AI assistant need to be fetched. Can be used instead of user for group chats. | `group={groupObject}` | | LoadingStateView | Custom loading state view component to be displayed while fetching chat history | `LoadingStateView={() => }` | + + +--- + +## Next Steps + + + + Display the list of messages in a conversation + + + Overview of all AI-powered features + + + Display and manage the list of recent chats + + + Customize the appearance of UI Kit components + + diff --git a/ui-kit/react-native/apple-privacy-manifest-guide.mdx b/ui-kit/react-native/apple-privacy-manifest-guide.mdx index 73597ea68..4dbdb128a 100644 --- a/ui-kit/react-native/apple-privacy-manifest-guide.mdx +++ b/ui-kit/react-native/apple-privacy-manifest-guide.mdx @@ -1,33 +1,56 @@ --- title: "Apple Privacy Manifest" +description: "Configure the required Apple Privacy Manifest for CometChat React Native UI Kit to comply with App Store requirements." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| File location | `ios/YourApp/PrivacyInfo.xcprivacy` | +| Required APIs | `NSPrivacyAccessedAPICategoryFileTimestamp` (C617.1), `NSPrivacyAccessedAPICategoryUserDefaults` (CA92.1), `NSPrivacyAccessedAPICategorySystemBootTime` (35F9.1), `NSPrivacyAccessedAPICategoryDiskSpace` (E174.1) | +| Purpose | Configure required Apple Privacy Manifest for App Store compliance | +| Related | [Getting Started](/ui-kit/react-native/react-native-cli-integration) · [Expo Integration](/ui-kit/react-native/expo-integration) · [All Guides](/ui-kit/react-native/guide-overview) | + + + ## Overview -The Apple Privacy Manifest plays a critical role in enhancing privacy and transparency for apps on Apple's platforms. As part of Apple's commitment to user privacy and data security, they introduced a new feature called the "App Privacy Details" section, which is essentially a 'privacy label' for each app. +The Apple Privacy Manifest enhances privacy and transparency for apps on Apple's platforms. As part of Apple's commitment to user privacy and data security, they introduced the "App Privacy Details" section — a privacy label for each app. + +The privacy manifest is a property list that records: -The privacy manifest is a property list that records the following information: +- The types of data collected by an app or third-party SDK +- The required reasons APIs an app or third-party SDK uses -* The types of data collected by an app or third-party SDK. -* The required reasons APIs an app or third-party SDK uses. +For each type of data an app or third-party SDK collects and category of required reasons API it uses, the app or SDK needs to record the reasons in its bundled privacy manifest file. -For each type of data an app or third-party SDK collects and category of required reasons API it uses, the app or third-party SDK needs to record the reasons in its bundled privacy manifest file. +--- -## React Native UIkit's Privacy Manifest +## React Native UI Kit Privacy Requirements -If you are using React Native UI Kit you need to add the following entries to your Privacy Manifest File. +If you are using the React Native UI Kit, you need to add the following entries to your Privacy Manifest file. -1. **React Native** +### Dependencies Requiring Privacy Declarations - React Native as a framework uses a few of the APIs that need to be added to your application. you can find more information on their GitHub [thread](https://github.com/react-native-community/discussions-and-proposals/discussions/776). +1. **React Native Framework** + + React Native uses several APIs that require privacy declarations. See the React Native community [discussion](https://github.com/react-native-community/discussions-and-proposals/discussions/776) for more details. 2. **SPTPersistentCache** + + The React Native UI Kit uses a native module (a fork of react-native-video) that has an internal dependency on SPTPersistentCache. This library uses one of the APIs listed by Apple. + +--- - React Native UI Kit uses a Native Module which is a fork of react-native-video library. This native module has an internal dependency on SPTPersistentCache. This library uses one of the APIs listed by Apple. +## Privacy Manifest File -Below is the finalized Privacy Manifest that should be included in your application for seamless integration and adherence to privacy regulations +Below is the complete Privacy Manifest that should be included in your application: -```xml PrivacyInfo.xcprivacy + + +```xml @@ -74,29 +97,66 @@ Below is the finalized Privacy Manifest that should be included in your applicat ``` + + -## Steps to Create a Privacy Manifest +--- -To add the privacy manifest to your application. You will need to open Xcode, +## Creating the Privacy Manifest -1. Choose `File > New > File...` + + + Open Xcode and choose **File > New > File...** - - - -2. Scroll down to the Resource section. Select the App Privacy file type, click `Next`. + + Xcode File Menu + + - - - -3. Select the target, then click `Create`. + + Scroll down to the **Resource** section, select the **App Privacy** file type, and click **Next**. - - - -4. By default, the file is named `PrivacyInfo.xcprivacy`. Don’t change the filename. -5. This will create an empty `Privacy Manifest` file. You need to replace the content of the file with the manifest shared above. + + Select App Privacy File Type + + + + + Select your app target, then click **Create**. + + + Select Target + + + + + By default, the file is named `PrivacyInfo.xcprivacy`. Do not change this filename. + + + + This creates an empty Privacy Manifest file. Replace the content with the manifest XML provided above. + + + Privacy Manifest Content + + + + +--- - - - +## Next Steps + + + + Complete UI Kit setup guide + + + Configure for Expo development builds + + + Browse all feature and formatter guides + + + Explore all available components + + \ No newline at end of file diff --git a/ui-kit/react-native/call-buttons.mdx b/ui-kit/react-native/call-buttons.mdx index 85d122a92..0d3688011 100644 --- a/ui-kit/react-native/call-buttons.mdx +++ b/ui-kit/react-native/call-buttons.mdx @@ -1,244 +1,250 @@ --- title: "Call Buttons" +description: "Add voice and video call buttons with CometChatCallButtons component in React Native UI Kit, enabling users to initiate calls directly." --- -## Overview + +```json +{ + "component": "CometChatCallButtons", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatCallButtons } from \"@cometchat/chat-uikit-react-native\";", + "description": "Voice and video call buttons that initiate calls to users or groups.", + "props": { + "data": { + "user": { + "type": "CometChat.User", + "note": "User object for one-on-one calls" + }, + "group": { + "type": "CometChat.Group", + "note": "Group object for group calls" + } + }, + "callbacks": { + "onError": "(error: CometChat.CometChatException) => void" + }, + "visibility": { + "hideVoiceCallButton": { "type": "boolean", "default": false }, + "hideVideoCallButton": { "type": "boolean", "default": false } + }, + "configuration": { + "callSettingsBuilder": "Callback to configure call settings", + "outgoingCallConfiguration": "Configuration for outgoing call component" + } + }, + "events": [ + { + "name": "ccCallRejected", + "payload": "{ call }", + "description": "Initiated call rejected by receiver" + }, + { + "name": "ccCallFailled", + "payload": "{ call }", + "description": "Error occurred during initiated call" + }, + { + "name": "ccOutgoingCall", + "payload": "{ call }", + "description": "User initiates a voice/video call" + } + ], + "compositionExample": { + "description": "Call buttons for message header", + "components": [ + "CometChatCallButtons", + "CometChatOutgoingCall" + ], + "flow": "Button press initiates call -> OutgoingCall screen displayed" + } +} +``` + + +## Where It Fits -The `CometChatCallButtons` is a [Component](/ui-kit/react-native/components-overview#components) provides users with the ability to make calls, access call-related functionalities, and control call settings. Clicking this button typically triggers the call to be placed to the desired recipient. +`CometChatCallButtons` is a [Component](/ui-kit/react-native/components-overview#components) that provides users with the ability to make calls, access call-related functionalities, and control call settings. Clicking this button typically triggers the call to be placed to the desired recipient. -*** - -## Usage - -### Integration +--- -The `CometChatCallButtons` is a [Component](/ui-kit/react-native/components-overview#components) provides users with the ability to make calls, access call-related functionalities, and control call settings. Clicking this button typically triggers the call to be placed to the desired recipient. +## Minimal Render - - -```tsx +```tsx lines import { CometChatCallButtons } from "@cometchat/chat-uikit-react-native"; -//code -return ; -``` - +function CallButtonsDemo() { + return ; +} +``` - +--- -*** +## Actions and Events -### Actions +### Callback Props -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +#### onError -##### onError +Fires on internal errors (network failure, auth issue, SDK exception). -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Call Button component. +```tsx lines +onError?: (e: CometChat.CometChatException) => void +``` - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatCallButtons } from "@cometchat/chat-uikit-react-native"; -//code -const onErrorHandler = (error: CometChat.CometChatException) => { - //handle Error -}; +function CallButtonsWithError() { + const handleError = (e: CometChat.CometChatException) => { + console.error("CallButtons error:", e); + }; -return ; + return ; +} ``` - - - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. - -The `CometChatCallButtons` component does not have any exposed filters. +### Global UI Events -*** +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Add listeners and remove them on cleanup. -### Events +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccCallRejected` | Initiated call is rejected by the receiver | `{ call }` | +| `ccCallFailled` | Error occurs during the initiated call | `{ call }` | +| `ccOutgoingCall` | User initiates a voice/video call | `{ call }` | -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +When to use: sync external UI with call state changes. For example, update a call status indicator, show notifications, or log call events. -The list of events emitted by the `Call Buttons` component is as follows. - -| Event | Description | -| ------------------ | ---------------------------------------------------------------------------- | -| **ccCallRejected** | This event is triggered when the initiated call is rejected by the receiver. | -| **ccCallFailled** | This event is triggered when an error occurs during the intiated call. | -| **ccOutgoingCall** | This event is triggered when the user initiates a voice/video call. | - - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; - -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallRejected: ({ call }) => { - //code - }, -}); - -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccOutgoingCall: ({ call }) => { - //code - }, -}); - -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallFailled: ({ call }) => { - //code - }, -}); -``` - - - - - -*** - - - -```tsx +```tsx lines +import { useEffect } from "react"; import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.removeCallListener("CALL_LISTENER_ID"); -``` - - +function useCallEvents() { + useEffect(() => { + const listenerId = "CALL_EVENTS_" + Date.now(); - - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. - - - -```tsx -import { - CometChatCallButtons, - useTheme, -} from "@cometchat/chat-uikit-react-native"; -//code -const theme: CometChatTheme = useTheme(); -//more code -return ( - { + console.log("Call rejected:", call); }, - audioCallButtonIconContainerStyle: { - backgroundColor: theme.color.extendedPrimary100, - paddingHorizontal: theme.spacing.padding.p4, - paddingVertical: theme.spacing.padding.p2, - borderRadius: 8, + ccOutgoingCall: ({ call }) => { + console.log("Outgoing call:", call); }, - videoCallButtonIconStyle: { - tintColor: theme.color.primary, + ccCallFailled: ({ call }) => { + console.log("Call failed:", call); }, - videoCallButtonIconContainerStyle: { - backgroundColor: theme.color.extendedPrimary100, - paddingHorizontal: theme.spacing.padding.p4, - paddingVertical: theme.spacing.padding.p2, - borderRadius: 8, - }, - }} - /> -); + }); + + return () => { + CometChatUIEventHandler.removeCallListener(listenerId); + }; + }, []); +} ``` - +--- + +## Styling - +Using Style you can customize the look and feel of the component in your app. Pass a styling object as a prop to the `CometChatCallButtons` component. -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | -| **group** | Used to set the group object for Call Buttons | `group?: CometChat.Group` | -| **user** | Sets the user object for Call Buttons | `user?: CometChat.User` | -| **hideVoiceCall** | Used to hide Voice Call | \`hideVoiceCall?: boolean | -| **hideVideoCall** | Used to hide Video Call | \`hideVideoCall?: boolean | -| **callSettingsBuilder** | Sets the call settings builder callback function. This callback is responsible for configuring the call settings based on the user, group, and call type (audio/video). | `callSettingsBuilder={callSettingsBuilderObject}` | -| **outgoingCallConfiguration** | Sets the configurations for outgoing call component. | `outgoingCallConfiguration={outgoingCallConfigurationObject}` | - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -The `CometChatCallButtons` component does not provide additional functionalities beyond this level of customization. - -*** - -## Configurations +```tsx lines +import { + CometChatCallButtons, + useTheme, +} from "@cometchat/chat-uikit-react-native"; -[Configurations](/ui-kit/android/components-overview#configurations) offer the ability to customize the properties of each individual component within a Composite Component. +function StylingDemo() { + const theme = useTheme(); + + return ( + + ); +} +``` -* `Configurations` expose properties that are available in its individual components. +### Visibility Props -*** +| Property | Description | Code | +| --- | --- | --- | +| `hideVoiceCallButton` | Toggle visibility of the voice call button | `hideVoiceCallButton?: boolean` | +| `hideVideoCallButton` | Toggle visibility of the video call button | `hideVideoCallButton?: boolean` | -#### Outgoing Call +### Outgoing Call Configuration -You can customize the properties of the Outgoing Call component by making use of the `OutgoingCallConfiguration`. You can accomplish this by employing the `OutgoingCallConfiguration` as demonstrated below: +You can customize the properties of the Outgoing Call component by making use of the `outgoingCallConfiguration` prop: - - -```tsx +```tsx lines import { CometChatCallButtons, OutgoingCallConfiguration, } from "@cometchat/chat-uikit-react-native"; -//code -const theme: CometChatTheme = useTheme(); -//more code -const getOutgoingCallConfig = () => { - return new OutgoingCallConfiguration({ - disableSoundForCalls: true, - }); -}; -return ( - -); + +function OutgoingCallConfigDemo() { + const getOutgoingCallConfig = () => { + return new OutgoingCallConfiguration({ + disableSoundForCalls: true, + }); + }; + + return ( + + ); +} ``` - +All exposed properties of `OutgoingCallConfiguration` can be found under [Outgoing Call](/ui-kit/react-native/outgoing-call). - +--- -All exposed properties of `OutgoingCallConfiguration` can be found under [Outgoing Call](/ui-kit/react-native/outgoing-call). +## Next Steps + + + + Display and handle incoming calls + + + Display and manage outgoing calls + + + View call history and logs + + + Overview of all calling features + + diff --git a/ui-kit/react-native/call-features.mdx b/ui-kit/react-native/call-features.mdx index 7d3fef3d8..df77ad227 100644 --- a/ui-kit/react-native/call-features.mdx +++ b/ui-kit/react-native/call-features.mdx @@ -1,14 +1,48 @@ --- title: "Call" +description: "Integrate one-on-one and group audio/video calling into your React Native app using CometChat's Calls SDK and prebuilt UI components." --- -CometChat’s Calls feature offers advanced functionality for seamlessly integrating one-on-one and group audio/video calling into your application. This document provides a technical overview of how these features are implemented using the React Native UI Kit. + +**Quick Reference for AI Agents & Developers** + +```bash +# Install the Calls SDK (required for calling features) +npm install @cometchat/calls-sdk-react-native +``` + +```tsx +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; + +// Register a call listener to handle incoming calls +CometChat.addCallListener( + "call-listener-id", + new CometChat.CallListener({ + onIncomingCallReceived: (call: CometChat.Call) => { + console.log("Incoming call:", call); + }, + }) +); +``` + +- **Incoming Call** → [CometChatIncomingCall](/ui-kit/react-native/incoming-call) +- **Outgoing Call** → [CometChatOutgoingCall](/ui-kit/react-native/outgoing-call) +- **Call Buttons** → [CometChatCallButtons](/ui-kit/react-native/call-buttons) +- **Call Logs** → [CometChatCallLogs](/ui-kit/react-native/call-logs) + + +CometChat's Calls feature offers advanced functionality for seamlessly integrating one-on-one and group audio/video calling into your application. This document provides a technical overview of how these features are implemented using the React Native UI Kit. + + +**Calling features** require installing `@cometchat/calls-sdk-react-native` separately. The UI Kit auto-detects it and enables call UI components. + ## Integration -First, make sure that you've correctly integrated the UI Kit library into your project. If you haven't done this yet or are facing difficulties, refer to our [Getting Started](/ui-kit/react-native/getting-started) guide. This guide will walk you through a step-by-step process of integrating our UI Kit into your React Native project. +First, make sure that you've correctly integrated the UI Kit library into your project. If you haven't done this yet or are facing difficulties, refer to the [Getting Started](/ui-kit/react-native/getting-started) guide. -Once you've successfully integrated the UI Kit, the next step is to add the CometChat Calls SDK to your project. This is necessary to enable the calling features in the UI Kit. Here's how you do it: +Once you've successfully integrated the UI Kit, the next step is to add the CometChat Calls SDK to your project. This is necessary to enable the calling features in the UI Kit: @@ -20,26 +54,17 @@ npm install @cometchat/calls-sdk-react-native -Once the dependency is added, the React Native UI Kit will automatically detect it and enable calling features. Your application will now support both audio and video calls and the [CallButtons](/ui-kit/react-native/call-buttons) component will appear within the [MessageHeader](/ui-kit/react-native/message-header) component. - - - -![Image](/images/81959c4b-Calling-ee689247c8cdd512c520b85f30683ad8.png) +Once the dependency is added, the React Native UI Kit will automatically detect it and enable calling features. Your application will now support both audio and video calls, and the [CallButtons](/ui-kit/react-native/call-buttons) component will appear within the [MessageHeader](/ui-kit/react-native/message-header) component. - - - -![Image](/images/bae9d77f-call_overview_cometchat_screens-a20afca1663c9bd893005bd9bb0fffeb.png) - - - - + + + -## Add necessary permissions +## Add Necessary Permissions -### Android: +### Android -Go to AndroidManifest.xml located in the react-native/app/src/main of your React Native project and add the following permissions: +Open `AndroidManifest.xml` located at `android/app/src/main` in your React Native project and add the following permissions: @@ -65,9 +90,9 @@ Go to AndroidManifest.xml located in the react-native/app/src/main of your React -### iOS: +### iOS -Open Info.plist located in the ios/\{appname} of your React Native project and add the following entries: +Open `Info.plist` located at `ios/{appname}` in your React Native project and add the following entries: @@ -88,9 +113,9 @@ Open Info.plist located in the ios/\{appname} of your React Native project and a -## Setup minimum Android and iOS versions +## Setup Minimum Android and iOS Versions -For Android go to app-level build.gradle and change minSdkVersion to 24 and the targetSdkVersion and compileSdkVersion to 33. +For Android, open the app-level `build.gradle` and set `minSdkVersion` to 24, and both `targetSdkVersion` and `compileSdkVersion` to 33. @@ -115,23 +140,20 @@ android { -For iOS you can open xcworkspace in XCode modify the IPHONEOS\_DEPLOYMENT\_TARGET to 12.0 +For iOS, open the `.xcworkspace` in Xcode and set `IPHONEOS_DEPLOYMENT_TARGET` to 12.0. -or you can specify it in the post\_install hook of the Podfile +Alternatively, you can specify it in the `post_install` hook of the Podfile: ```ruby post_install do |installer| installer.pods_project.targets.each do |target| - flutter_additional_ios_build_settings(target) target.build_configurations.each do |build_configuration| - - build_configuration.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0' - - build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' - build_configuration.build_settings['ENABLE_BITCODE'] = 'NO' - end + build_configuration.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '12.0' + build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' + build_configuration.build_settings['ENABLE_BITCODE'] = 'NO' + end end end ``` @@ -142,15 +164,15 @@ end ## Add the Call Listeners -In addition to CallButtons, the Calls UI Kit offers fully functional UI components for handling Incoming, Outgoing, and Ongoing calls. To receive call events in your desired component or screen, you must register a call listener using the addCallListener() method. The onIncomingCallReceived() event is triggered whenever an incoming call is received. +In addition to CallButtons, the Calls UI Kit offers fully functional UI components for handling Incoming, Outgoing, and Ongoing calls. To receive call events in your desired component or screen, you must register a call listener using the `addCallListener()` method. The `onIncomingCallReceived()` event is triggered whenever an incoming call is received. - + ```tsx import React, { useEffect, useRef, useState } from "react"; -import { SafeAreaView } from "react-native"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; +import { CometChatIncomingCall, CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; // Track whether the user is logged in const [loggedIn, setLoggedIn] = useState(false); @@ -190,13 +212,23 @@ const App = (): React.ReactElement => { }) ); - // Cleanup: remove the call listener when the component unmounts or before re-running + // Register UI Kit-level call listener to handle call end events + CometChatUIEventHandler.addCallListener(listenerID, { + ccCallEnded: () => { + incomingCall.current = null; + setCallReceived(false); + }, + }); + + // Cleanup: remove both listeners when the component unmounts or before re-running return () => { CometChat.removeCallListener(listenerID); + CometChatUIEventHandler.removeCallListener(listenerID); }; }, [loggedIn]); // Re-run effect if the login state changes return ( + {/* Render the incoming call UI when logged in and a call has been received */} {loggedIn && callReceived && incomingCall.current ? ( @@ -210,6 +242,7 @@ const App = (): React.ReactElement => { /> ) : null} + ); }; ``` @@ -234,7 +267,7 @@ When a call is made to a user, the Incoming Call component triggers and displays The [Outgoing Call](/ui-kit/react-native/outgoing-call) component of the CometChat UI Kit is designed to manage the outgoing call process within your application. When a user initiates an audio or video call to another user or group, this component displays an outgoing call screen, showcasing information about the recipient and the call status. -Importantly, the Outgoing Call component is smartly designed to transition automatically into the ongoing call screen once the receiver accepts the call. This ensures a smooth flow from initiating the call to engaging in a conversation, without any additional steps required from the user. +The Outgoing Call component automatically transitions into the ongoing call screen once the receiver accepts the call. This ensures a smooth flow from initiating the call to engaging in a conversation, without any additional steps required from the user. @@ -242,8 +275,27 @@ Importantly, the Outgoing Call component is smartly designed to transition autom ### Call Logs -[Call Logs](/ui-kit/react-native/call-logs) component provides you with the records call events such as who called who, the time of the call, and the duration of the call. This information can be fetched from the CometChat server and displayed in a structured format for users to view their past call activities. +The [Call Logs](/ui-kit/react-native/call-logs) component provides records of call events such as who called whom, the time of the call, and the duration. This information can be fetched from the CometChat server and displayed in a structured format for users to view their past call activities. + +--- + +## Next Steps + + + + Handle incoming audio and video calls + + + Manage outgoing call screens and transitions + + + Add call action buttons to your chat header + + + Display call history and past call activities + + diff --git a/ui-kit/react-native/call-logs.mdx b/ui-kit/react-native/call-logs.mdx index 58999a62b..855073890 100644 --- a/ui-kit/react-native/call-logs.mdx +++ b/ui-kit/react-native/call-logs.mdx @@ -1,8 +1,66 @@ --- title: "Call Logs" +description: "Display and manage the list of call history with CometChatCallLogs component in React Native UI Kit, including missed, received, and outgoing calls." --- -## Overview + +```json +{ + "component": "CometChatCallLogs", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatCallLogs } from \"@cometchat/chat-uikit-react-native\";", + "description": "Scrollable list of call history showing missed, received, and outgoing calls.", + "props": { + "data": { + "callLogRequestBuilder": { + "type": "CallLogRequestBuilder", + "note": "Pass the builder, not the result of .build()" + }, + "datePattern": { + "type": "DatePattern", + "note": "Custom date format for call timestamps" + } + }, + "callbacks": { + "onItemPress": "(call: any) => void", + "onItemLongPress": "(prop: { call: any }) => void", + "onCallIconPress": "(item: any) => void", + "onBack": "() => void", + "onError": "(error: CometChat.CometChatException) => void", + "onLoad": "(list: any[]) => void", + "onEmpty": "() => void" + }, + "visibility": { + "showBackButton": { "type": "boolean", "default": true }, + "hideError": { "type": "boolean", "default": false }, + "hideHeader": { "type": "boolean", "default": false }, + "hideLoadingState": { "type": "boolean", "default": false } + }, + "viewSlots": { + "ItemView": "(call: any) => JSX.Element", + "LeadingView": "(call: any) => JSX.Element", + "TitleView": "(call: any) => JSX.Element", + "SubtitleView": "(call: any) => JSX.Element", + "TrailingView": "(call: any, defaultOnPress?: (call: any) => void) => JSX.Element", + "LoadingView": "() => JSX.Element", + "EmptyView": "() => JSX.Element", + "ErrorView": "(e: CometChat.CometChatException) => JSX.Element", + "AppBarOptions": "() => JSX.Element" + } + }, + "compositionExample": { + "description": "Call history list with call-back functionality", + "components": [ + "CometChatCallLogs", + "CometChatOutgoingCall" + ], + "flow": "onItemPress initiates call to participant, onCallIconPress triggers call-back" + } +} +``` + + +## Where It Fits `CometChatCallLogs` is a [Component](/ui-kit/react-native/components-overview#components) that shows the list of Call Logs available. By default, names are shown for all listed users, along with their avatars if available. @@ -10,639 +68,491 @@ title: "Call Logs" -## Usage - -### Integration +--- -`CometChatCallLogs` being a wrapper component, offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. +## Minimal Render - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -return ; -``` - - - - - -### Actions - -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -##### onItemPress -`onItemPress` is triggered when you click on a ListItem of the Call Logs component. By default it initiate a call to the participant associated with the respective ListItem. You can override this action using the following code snippet. - - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getItemPresshandler = (call: any) => { - //code -}; -return ( - -); +function CallLogsDemo() { + return ; +} ``` - - - - -*** +--- -##### onItemLongPress +## Filtering Call Logs -Function executed when a callLog item is long-pressed, allowing additional actions like delete or select. +Pass a `CallLogRequestBuilder` to `callLogRequestBuilder`. Pass the builder instance — not the result of `.build()`. - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const onItemLongPressHandler = (i: any) => { - //handle long press -}; - -return ; -``` +import { CallLogRequestBuilder } from "@cometchat/chat-sdk-react-native"; - +function FilteredCallLogs() { + const callLogRequestBuilder = new CallLogRequestBuilder() + .setLimit(20) + .setCallStatus("cancelled") + .setAuthToken(loggedInUser.getAuthToken()); - - -*** + return ( + + ); +} +``` -##### onCallIconPress +### Filter Recipes - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getOnCallIconPressHandler = (call: any) => { - //handle call icon press -}; +| Recipe | Code | +| --- | --- | +| Limit to 20 per page | `new CallLogRequestBuilder().setLimit(20)` | +| Only cancelled calls | `new CallLogRequestBuilder().setCallStatus("cancelled")` | +| Only incoming calls | `new CallLogRequestBuilder().setCallDirection("incoming")` | +| Only outgoing calls | `new CallLogRequestBuilder().setCallDirection("outgoing")` | +| Calls with recordings | `new CallLogRequestBuilder().setHasRecording(true)` | +| Filter by user UID | `new CallLogRequestBuilder().setUid("user_uid")` | -return ( - -); -``` +--- - +## Actions and Events - +### Callback Props -*** +#### onItemPress -##### onBack +Fires when a call log row is tapped. By default initiates a call to the participant. -`onBack` is triggered when you press the back button in the app bar. You can override this action using the following code snippet. +```tsx lines +onItemPress?: (call: any) => void +``` - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const onBackHandler = () => { - //handle back -}; -return ; -``` +function CallLogsWithPress() { + const handleItemPress = (call: any) => { + console.log("Selected call:", call); + }; - + return ; +} +``` - +#### onItemLongPress -##### OnError +Fires when a call log item is long-pressed, allowing additional actions like delete or select. -This action doesn't change the behavior of the component but rather listens for any errors that occur in the callLogs component. +```tsx lines +onItemLongPress?: (prop: { call: any }) => void +``` - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const onErrorHandler = (e: CometChat.CometChatException) => { - //handle back -}; -return ; -``` +function CallLogsWithLongPress() { + const handleLongPress = (prop: { call: any }) => { + console.log("Long pressed:", prop.call); + }; - + return ; +} +``` - +#### onCallIconPress -*** +Fires when the call icon is pressed. -### Filters +```tsx lines +onCallIconPress?: (item: any) => void +``` -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -##### CallLogRequestBuilder +function CallLogsWithCallIcon() { + const handleCallIconPress = (call: any) => { + console.log("Call icon pressed:", call); + }; -The [CallLogRequestBuilder](/sdk/react-native/call-logs) enables you to filter and customize the Call Log based on available parameters in [CallLogRequestBuilder](/sdk/react-native/call-logs). This feature allows you to create more specific and targeted queries when fetching the call logs. The following are the parameters available in [CallLogRequestBuilder](/sdk/react-native/call-logs) + return ; +} +``` -| Methods | Type | Description | -| -------------------- | ---------- | ------------------------------------------------------------ | -| **setLimit** | number | Specifies the number of call logs to fetch. | -| **setCallType** | String | Sets the type of calls to fetch (call or meet). | -| **setCallStatus** | callStatus | Sets the status of calls to fetch (initiated, ongoing, etc.) | -| **setHasRecording** | boolean | Sets whether to fetch calls that have recordings. | -| **setCallCategory** | string | Sets the category of calls to fetch (call or meet). | -| **setCallDirection** | string | Sets the direction of calls to fetch (incoming or outgoing) | -| **setUid** | string | Sets the UID of the user whose call logs to fetch. | -| **setGuid** | string | Sets the GUID of the user whose call logs to fetch. | -| **setAuthToken** | string | Sets the Auth token of the logged-in user. | +#### onBack -**Example** +Fires when the back button in the app bar is pressed. -In the example below, we're filtering Call Logs to show only canceled calls and setting the limit to five. +```tsx lines +onBack?: () => void +``` - - -```tsx -import { - CometChat, - CometChatCalls, - CallLogRequestBuilder, -} from "@cometchat/chat-sdk-react-native"; +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -function App(): React.JSX.Element { - const [loggedInUser, setLoggedInUser] = useState(); - useEffect(() => { - //code - CometChatUIKit.login({ uid: "uid" }) - .then(async (user: CometChat.User) => { - setLoggedInUser(user); - }) - .catch((error: any) => { - //handle error - }); - }, []); - +function CallLogsWithBack() { return ( - <> - {loggedInUser && ( - - )} - + { + console.log("Back pressed"); + }} + /> ); } ``` - - - - -*** - -### Events - -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +#### onError -The `CometChatCallLogs` component does not have any exposed events. +Fires on internal errors (network failure, auth issue, SDK exception). -*** +```tsx lines +onError?: (e: CometChat.CometChatException) => void +``` -## Customization +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -To fit your app's design requirements, you can customize the appearance of the CallLog component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +function CallLogsWithError() { + return ( + { + console.error("CallLogs error:", error); + }} + /> + ); +} +``` -### Style +#### onLoad -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Fires when the list is successfully fetched and loaded. - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -return ( - -); +```tsx lines +onLoad?: (list: any[]) => void ``` - +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; - +function CallLogsWithLoad() { + const handleLoad = (list: any[]) => { + console.log("Call logs loaded:", list.length); + }; - - - + return ; +} +``` -*** +#### onEmpty -### Functionality +Fires when the call log list is empty. -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +```tsx lines +onEmpty?: () => void +``` -| Property | Description | Code | -| ----------------------------- | ---------------------------------------------------- | ------------------------------------------------------------- | -| **datePattern** | Used to set custom date pattern | `datePattern?: DatePattern` | -| **hideBackButton** | Used to show/hide the back button | `hideBackButton?: boolean` | -| **hideError** | Used to hide errors | `hideError?: boolean` | -| **outgoingCallConfiguration** | Sets the configurations for outgoing call component. | `outgoingCallConfiguration={outgoingCallConfigurationObject}` | -| **hideHeader** | Used to toggle visibility of header | `hideHeader={true}` | -| **hideLoadingState** | Used to toggle visibility of Loading state | `hideLoadingState={true}` | +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -*** +function CallLogsWithEmpty() { + return ( + { + console.log("No call logs available"); + }} + /> + ); +} +``` -### Advanced +--- -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +## Custom View Slots -#### LoadingView +Each slot replaces a section of the default UI. Slots that accept a call parameter receive the call log object for that row. -Allows setting a custom loading view when fetching call logs. +| Slot | Signature | Replaces | +| --- | --- | --- | +| `ItemView` | `(call: any) => JSX.Element` | Entire list item row | +| `LeadingView` | `(call: any) => JSX.Element` | Avatar / left section | +| `TitleView` | `(call: any) => JSX.Element` | Caller name / title text | +| `SubtitleView` | `(call: any) => JSX.Element` | Call type / details | +| `TrailingView` | `(call: any, defaultOnPress?) => JSX.Element` | Duration / right section | +| `LoadingView` | `() => JSX.Element` | Loading spinner | +| `EmptyView` | `() => JSX.Element` | Empty state | +| `ErrorView` | `(e: CometChat.CometChatException) => JSX.Element` | Error state | +| `AppBarOptions` | `() => JSX.Element` | Header bar options | -Use Cases: +### LoadingView -* Display a spinner animation while loading. -* Show a "Fetching Call History..." message. -* Use a shimmer effect for better UI experience. +Custom view displayed when data is being fetched. - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getLoadingView = () => { - //return jsx; -}; -return ; +```tsx lines +LoadingView?: () => JSX.Element ``` - - - +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; +import { Text } from "react-native"; -#### EmptyView +function LoadingViewDemo() { + const getLoadingView = (): JSX.Element => { + return Loading call logs...; + }; -Defines a custom view when no call logs are available. + return ; +} +``` -Use Cases: +### EmptyView -* Show a friendly message like "No calls yet!". -* Offer quick actions like "Make a Call". -* Display an illustration/image. +Custom view displayed when there are no call logs. - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getEmptyView = () => { - //return jsx; -}; -return ; +```tsx lines +EmptyView?: () => JSX.Element ``` - - - - -*** +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; +import { Text } from "react-native"; -#### ErrorView +function EmptyViewDemo() { + const getEmptyView = (): JSX.Element => { + return No calls yet. Make your first call!; + }; -Allows setting a custom error state view when fetching call logs fails. + return ; +} +``` -Use Cases: +### ErrorView -* Display a retry button. -* Show a network issue message. -* Provide a troubleshooting guide. +Custom view displayed when an error occurs. - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getErrorView = (e: CometChat.CometChatException) => { - //return jsx; -}; -return ; +```tsx lines +ErrorView?: (e: CometChat.CometChatException) => JSX.Element ``` - - - +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { Text } from "react-native"; -#### ItemView +function ErrorViewDemo() { + const getErrorView = (e: CometChat.CometChatException): JSX.Element => { + return Error loading calls. Please try again.; + }; -Allows setting a custom layout for each call log item. + return ; +} +``` -Use Cases: +### ItemView -* Customize the entire call log card. -* Display additional contact details. -* Use a two-column design for better readability. +Custom view for the entire list item row. - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getItemView = (call: any) => { - //return jsx; -}; -return ; +```tsx lines +ItemView?: (call: any) => JSX.Element ``` - - - - -#### TitleView - -Allows setting a custom title view, typically used for the caller’s name or number. - -Use Cases: - -* Display caller’s full name. -* Show a business label for saved contacts. -* Use bold text for unknown numbers. - - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getTitleView = (call: any) => { - //return jsx; -}; -return ; -``` - - - - - -#### LeadingView - -Customizes the leading view, usually the caller’s avatar or profile picture. - -Use Cases: - -* Display a profile picture. -* Show a call type icon (missed, received, dialed). -* Indicate call status (e.g., missed calls in red). +import { View, Text } from "react-native"; + +function ItemViewDemo() { + const getItemView = (call: any): JSX.Element => { + return ( + + {call.getInitiator().getName()} + {call.getStatus()} + + ); + }; - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getLeadingView = (call: any) => { - //return jsx; -}; -return ; + return ; +} ``` - - - - -#### SubtitleView - -Enables customizing the subtitle view, usually used for additional call details. +### SubtitleView -Use Cases: +Custom view for the call type / details. -* Display call type (Missed, Received, Outgoing). -* Show network strength indicators. -* Include call duration in a more readable format. - - - -```tsx -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getSubtitleView = (call: any) => { - //return jsx; -}; -return ; +```tsx lines +SubtitleView?: (call: any) => JSX.Element ``` - - - - -**Example** - -*** - -#### TrailingView - -Customizes the trailing section, typically for call duration or actions. - -Use Cases: - -* Display call duration. -* Add a "Call Again" button. -* Show call timestamps. - - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getTrailingView = (call: any) => { - //return jsx; -}; -return ; +import { Text } from "react-native"; + +function SubtitleViewDemo() { + const getSubtitleView = (call: any): JSX.Element => { + return ( + + {call.getStatus()} • {call.getDuration()}s + + ); + }; + + return ; +} ``` - +### TrailingView - +Custom view for the duration / right section. -**Example** +```tsx lines +TrailingView?: (call: any, defaultOnPress?: (call: any) => void) => JSX.Element +``` -#### AppBarOptions +```tsx lines +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; +import { TouchableOpacity, Text } from "react-native"; + +function TrailingViewDemo() { + const getTrailingView = (call: any, defaultOnPress?: (call: any) => void): JSX.Element => { + return ( + defaultOnPress?.(call)}> + 📞 Call Back + + ); + }; -You can set Custom `AppBarOptions` to the `CometChatConversations` widget. + return ; +} +``` -Use Cases: +### AppBarOptions -* Filter Call Logs +Custom view for the header bar options. - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code -const getAuxiliaryAppBarOptions = (): JSX.Element => { +import { TouchableOpacity, Image } from "react-native"; + +function AppBarOptionsDemo() { return ( - { - /* code */ + { + return ( + console.log("Filter pressed")}> + + + ); }} - > - - + /> ); -}; -return ( - -); +} ``` - - - - -#### options +--- -Defines the available actions users can perform on a call log entry, such as deleting, marking as spam, or calling back. +## Styling -Use Cases: +Using Style you can customize the look and feel of the component in your app. Pass a styling object as a prop to the `CometChatCallLogs` component. -* Provide quick call-back options. -* Allow users to block a number. -* Enable deleting multiple call logs. + + + - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code - -const setMyOptions = (call: CometChat.Call) => { - return [ - //options - ]; - }; - -return ( - -); +function StylingDemo() { + return ( + + ); +} ``` - - - +### Visibility Props -#### addOptions +| Property | Description | Code | +| --- | --- | --- | +| `showBackButton` | Toggle visibility of the back button in the app bar | `showBackButton?: boolean` | +| `hideError` | Hide error state on fetching call logs | `hideError?: boolean` | +| `hideHeader` | Toggle visibility for the toolbar/header bar | `hideHeader?: boolean` | +| `hideLoadingState` | Toggle visibility of loading state | `hideLoadingState?: boolean` | -Adds custom actions to the existing call log options. +### Outgoing Call Configuration -Use Cases: +You can customize the properties of the OutGoing Call by making use of the `outgoingCallConfiguration` prop: -* Add favorite/star call log option. -* Add favorite/star call log option. -* Provide an archive feature. - - - -```tsx +```tsx lines import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code - -const addOptions = (call: CometChat.Call) => { - return [ - //options - ]; - }; +import { Text } from "react-native"; - -return ( - -); +function OutgoingCallConfigDemo() { + return ( + { + return Outgoing Call; + }, + style: { + containerStyle: { + backgroundColor: '#FFE4EBF5', + }, + }, + }} + /> + ); +} ``` - - - - -## Customization - -Configurations offer the ability to customize the properties of each widget within a Composite Widget. - -CometChatCallLogs has CometChatOutgoingCall widget. Hence, each of these widgets will have its individual \`Configuration\`\`. - -* Configurations expose properties that are available in its individual widgets. - -### Outgoing Call - -You can customize the properties of the OutGoing Call by making use of the OutgoingCallConfiguration. You can accomplish this by employing the outgoingCallConfiguration props as demonstrated below: - -```javascript -import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; -//code +--- -return ( - { - return Outgoing Call; - }, - style: { - containerStyle: { - backgroundColor: 'FFE4EBF5', - }, - }, - }} - /> -); -``` +## Next Steps + + + + Display and handle incoming calls + + + Display and manage outgoing calls + + + Add voice and video call buttons to your UI + + + Overview of all calling features + + diff --git a/ui-kit/react-native/colors.mdx b/ui-kit/react-native/colors.mdx index 7abf53065..7a9ecba68 100644 --- a/ui-kit/react-native/colors.mdx +++ b/ui-kit/react-native/colors.mdx @@ -1,10 +1,81 @@ --- -title: "Colors" +title: "Color Resources" +sidebarTitle: "Colors" +description: "Complete reference of all color tokens available in the CometChat React Native UI Kit, including primary, neutral, alert, and semantic color palettes for light and dark modes." +--- + + + +| Field | Value | +| --- | --- | +| Goal | Override UI Kit color tokens to match a brand | +| Provider | `CometChatThemeProvider` — wrap app and pass `theme` prop | +| Import | `import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native";` | +| Override colors | `theme={{ light: { color: { primary: "#F76808", textPrimary: "#7f7f00" } } }}` | +| Key tokens | `primary` (brand/accent), `neutral50` (surfaces), `background1` (main bg), `textPrimary` | +| Extended colors | Auto-generated from `primary` (extendedPrimary50–900) unless explicitly overridden | +| Dark mode | `theme={{ dark: { color: { ... } } }}` — separate palette for dark theme | +| Constraints | Colors must be hex values, extended colors auto-derive from primary | +| Source | [GitHub theme types](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts) | [Color helper](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/CometChatThemeHelper.ts) | + + + +The UI Kit's color palette uses theme tokens for consistent styling. Override these tokens via `CometChatThemeProvider` to match your brand. + + +Prerequisites: +1. Wrap your app with `CometChatThemeProvider` +2. Colors must be supplied as hex values (e.g., `#F76808`) +3. Extended primary colors auto-generate from `primary` unless explicitly overridden + + +--- + +## Color Token Reference + +This table maps every commonly used token to what it visually controls. + +| Token | What It Controls | Default (Light) | Used By | +| --- | --- | --- | --- | +| `primary` | Brand accent, outgoing bubble bg, active states, buttons | `#6852D6` | Outgoing bubbles, send button, active tabs | +| `neutral50` | White surface | `#FFFFFF` | Background color 01, cards | +| `neutral100` | Light surface | `#FAFAFA` | Background color 02 | +| `neutral200` | Secondary surface | `#F5F5F5` | Background color 03 | +| `neutral300` | Incoming bubble background, borders | `#E8E8E8` | Incoming message bubbles, background color 04 | +| `neutral400` | Border dark | `#DCDCDC` | Borders, dividers | +| `neutral500` | Muted text, placeholders | `#A1A1A1` | Placeholder text, disabled states, icon secondary | +| `neutral600` | Secondary text | `#727272` | Timestamps, subtitles | +| `neutral700` | Tertiary text | `#5B5B5B` | Body text | +| `neutral800` | Strong text | `#434343` | Headings | +| `neutral900` | Strongest text | `#141414` | Text color primary | +| `background1` | Main app background | `neutral50` | Root container background | +| `background2` | Secondary/panel background | `neutral100` | Sidebars, panels | +| `background3` | Tertiary background | `neutral200` | Nested panels, cards | +| `background4` | Quaternary background | `neutral300` | Additional surface layer | +| `textPrimary` | Primary text color | `neutral900` | Main body text | +| `textSecondary` | Secondary/caption text | `neutral600` | Timestamps, subtitles | +| `textTertiary` | Tertiary text | `neutral500` | Hints, placeholders | +| `textHighlight` | Highlighted text | `primary` | Links, mentions | +| `iconPrimary` | Primary icon color | `neutral900` | Main icons | +| `iconSecondary` | Secondary icon color | `neutral500` | Inactive icons | +| `iconHighlight` | Highlighted icon color | `primary` | Active icons | +| `extendedPrimary50–900` | Primary color scale (lightest to darkest) | Auto-generated | Hover states, gradients, shades | +| `info` | Informational states | `#0B7BEA` | Info callouts, links | +| `warning` | Warning states | `#FFAB00` | Warning callouts | +| `success` | Success states | `#09C26F` | Online indicators, success messages | +| `error` | Error states | `#F44649` | Error messages, validation | +| `staticBlack` | Static black (doesn't change with theme) | `#141414` | Fixed dark elements | +| `staticWhite` | Static white (doesn't change with theme) | `#FFFFFF` | Fixed light elements | +| `sendBubbleBackground` | Outgoing bubble background | `primary` | Sent message bubbles | +| `sendBubbleText` | Outgoing bubble text | `staticWhite` | Sent message text | +| `receiveBubbleBackground` | Incoming bubble background | `neutral300` | Received message bubbles | +| `receiveBubbleText` | Incoming bubble text | `neutral900` | Received message text | + --- ## Overview -Colors in CometChatTheme allow you to maintain a consistent visual identity across your application by providing predefined colors for various UI elements, such as text, buttons, backgrounds, alerts, and more. These color definitions seamlessly adapt to both light and dark themes, ensuring an optimal user experience across different modes. +Colors in `CometChatTheme` allow you to maintain a consistent visual identity across your application by providing predefined colors for various UI elements, such as text, buttons, backgrounds, alerts, and more. These color definitions seamlessly adapt to both light and dark themes, ensuring an optimal user experience across different modes. The color resources are divided into the following categories: @@ -183,11 +254,11 @@ getBlendColorsPercentage(brightness: Brightness): { } ``` -For more details on how other colors are generated [Click Here](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/CometChatThemeHelper.ts). +For more details on how other colors are generated, [click here](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/CometChatThemeHelper.ts). -Extended primary colors, as well as background, text, button, and other UI colors, are automatically derived from the provided primary and neutral colors. However, any colors explicitly overridden in the theme via CometChatThemeProvider will take precedence over the generated values. +Extended primary colors, as well as background, text, button, and other UI colors, are automatically derived from the provided primary and neutral colors. However, any colors explicitly overridden in the theme via `CometChatThemeProvider` will take precedence over the generated values. @@ -206,6 +277,9 @@ Example: Changing the primary and textPrimary colors. ```ts +import { SafeAreaView } from "react-native-safe-area-context"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + return ( -To know more about theme structure, visit the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). +To learn more about the theme structure, visit the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). + +--- + +## Next Steps + + + + Learn how CometChatThemeProvider manages light and dark modes + + + Style individual message bubbles and their content + + + Translate UI strings and support multiple languages + + + Explore all available UI Kit components + + diff --git a/ui-kit/react-native/component-styling.mdx b/ui-kit/react-native/component-styling.mdx index 63ad991dd..623d8ab16 100644 --- a/ui-kit/react-native/component-styling.mdx +++ b/ui-kit/react-native/component-styling.mdx @@ -1,16 +1,77 @@ --- title: "Component Styling" +sidebarTitle: "Component Styling" +description: "Customize the appearance of individual CometChat React Native UI Kit components using theme overrides for colors, typography, icons, and layout styles." +--- + + + +| Field | Value | +| --- | --- | +| Goal | Style individual UI Kit components via theme overrides | +| Provider | `CometChatThemeProvider` — pass component styles in `theme` prop | +| Import | `import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native";` | +| Pattern | `theme={{ light: { : { ... } } }}` | +| Conversations | `conversationStyles: { itemStyle: { avatarStyle: { containerStyle: { borderRadius: 8 } } } }` | +| Users | `userStyles: { titleStyle: { color: "#F76808" }, itemStyle: { ... } }` | +| Groups | `groupStyles: { titleStyle: { ... }, itemStyle: { ... } }` | +| Message List | `messageListStyles: { containerStyle: { ... }, outgoingMessageBubbleStyles: { ... } }` | +| Message Composer | `messageComposerStyles: { sendIconContainerStyle: { ... }, attachmentIconStyle: { ... } }` | +| Precedence | Style prop > Custom theme > Default theme (deep merge) | +| Source | [GitHub theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts) | + + + +Style individual UI Kit components by passing component-specific style objects in the theme. + + +Prerequisites: +1. Wrap your app with `CometChatThemeProvider` +2. Component styles are passed via `theme={{ light: { : { ... } } }}` +3. Style props on components take precedence over theme styles + + +--- + +## Component Style Keys + +| Component | Theme Key | Common Style Properties | +| --- | --- | --- | +| Conversations | `conversationStyles` | `containerStyle`, `itemStyle`, `avatarStyle` | +| Users | `userStyles` | `titleStyle`, `titleSeparatorStyle`, `itemStyle` | +| Groups | `groupStyles` | `titleStyle`, `titleSeparatorStyle`, `itemStyle` | +| Group Members | `groupMemberStyle` | `titleStyle`, `titleSeparatorStyle`, `backButtonIconStyle` | +| Message Header | `messageHeaderStyles` | `titleTextStyle`, `avatarStyle`, `callButtonStyle` | +| Message List | `messageListStyles` | `containerStyle`, `incomingMessageBubbleStyles`, `outgoingMessageBubbleStyles` | +| Message Composer | `messageComposerStyles` | `sendIconContainerStyle`, `attachmentIconStyle`, `voiceRecordingIconStyle` | +| Thread Header | `threadHeaderStyles` | `containerStyle`, `replyCountBarStyle`, `messageBubbleContainerStyle` | +| Call Logs | `callLogsStyles` | `titleTextStyle`, `titleSeparatorStyle`, `itemStyle` | +| Incoming Call | `incomingCallStyle` | `containerStyle`, `avatarStyle`, `acceptCallButtonStyle`, `declineCallButtonStyle` | +| Outgoing Call | `outgoingCallStyle` | `avatarStyle`, `endCallButtonStyle` | +| Call Buttons | `callButtonStyles` | `audioCallButtonIconStyle`, `videoCallButtonIconStyle` | +| Avatar | `avatarStyle` | `containerStyle`, `imageStyle` | +| Badge | `badgeStyle` | `containerStyle`, `textStyle` | +| Status Indicator | `statusIndicatorStyle` | `containerStyleOnline`, `containerStyleOffline` | +| Date | `dateStyles` | `textStyle`, `containerStyle` | +| Receipt | `receiptStyles` | `readIconStyle`, `deliveredIconStyle`, `sentIconStyle` | +| Action Sheet | `actionSheetStyle` | `optionsItemStyle` | +| AI Chat History | `chatHistoryStyles` | `containerStyle`, `headerStyle`, `messageItemStyle` | +| Confirm Dialog | `confirmDialogStyles` | `containerStyle`, `titleStyle`, `messageStyle` | +| Media Recorder | `mediaRecorderStyle` | `animationStyle`, `playIconStyle`, `pauseIconStyle` | +| Message Information | `messageInformationStyles` | `containerStyle`, `titleStyle`, `messageBubbleContainerStyle` | +| Reaction List | `reactionListStyles` | `tabStyle`, `reactionListItemStyle` | + --- ## Overview -CometChat UIKit enables developers to seamlessly integrate customizable components into their applications. Each component is designed to ensure a consistent user experience while offering flexibility to adapt to your app’s design system. You can modify attributes such as colors, fonts, sizes, icons, and more using XML or programmatically. Below is a detailed guide for styling individual components within the UIKit. +CometChat UIKit enables developers to seamlessly integrate customizable components into their applications. Each component is designed to ensure a consistent user experience while offering flexibility to adapt to your app's design system. You can modify attributes such as colors, fonts, sizes, icons, and more using the theme provider or programmatically. Below is a detailed guide for styling individual components within the UIKit. ## Components ### Conversations -The `CometChatConversations` Component provides a list of recent chats, showing participants, message previews, and timestamps. It supports default themes while offering deep customization for text appearance, icons, and overall layout. With this component, you can create an intuitive and visually appealing chat list that matches your app’s branding. +The `CometChatConversations` component provides a list of recent chats, showing participants, message previews, and timestamps. It supports default themes while offering deep customization for text appearance, icons, and overall layout. With this component, you can create an intuitive and visually appealing chat list that matches your app's branding. @@ -22,6 +83,7 @@ import { CometChatUIKit, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; ///code return ( @@ -68,7 +130,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Users -The `CometChatUsers` Component displays a scrollable list of users. It is ideal for showcasing available contacts for messaging, calls, or group creation. Developers can style elements like user avatars, status indicators, and list backgrounds to align with their design guidelines. +The `CometChatUsers` component displays a scrollable list of users. It is ideal for showcasing available contacts for messaging, calls, or group creation. Developers can style elements like user avatars, status indicators, and list backgrounds to align with their design guidelines. @@ -79,6 +141,8 @@ import { CometChatUsers, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -130,7 +194,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Groups -The `CometChatGroups` Component allows you to display and interact with chat groups. Each group item highlights key details like the group name, participant count, and last active time. Customization options include avatar styles, fonts, borders, and background colors, ensuring the component blends seamlessly with your app. +The `CometChatGroups` component allows you to display and interact with chat groups. Each group item highlights key details like the group name, participant count, and last active time. Customization options include avatar styles, fonts, borders, and background colors, ensuring the component blends seamlessly with your app. @@ -141,6 +205,8 @@ import { CometChatGroups, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -192,7 +258,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Message Header -The `CometChatMessageHeader` Component provides essential information about the active chat, such as the recipient's name, avatar, and status (online/offline). It often includes options like back navigation, search, or menu buttons. Customization options allow you to style the header background, text appearance, and icons to match your app's overall design. +The `CometChatMessageHeader` component provides essential information about the active chat, such as the recipient's name, avatar, and status (online/offline). It often includes options like back navigation, search, or menu buttons. Customization options allow you to style the header background, text appearance, and icons to match your app's overall design. @@ -204,6 +270,8 @@ import { CometChatMessageHeader, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -281,7 +349,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Message List -The `CometChatMessageList` Component displays the sequence of messages in a conversation, supporting text, media, reactions, and more. It includes smooth scrolling, timestamps, and grouping for better readability. Developers can customize bubble colors, text appearance, timestamps, and alignment to provide a tailored chat experience. +The `CometChatMessageList` component displays the sequence of messages in a conversation, supporting text, media, reactions, and more. It includes smooth scrolling, timestamps, and grouping for better readability. Developers can customize bubble colors, text appearance, timestamps, and alignment to provide a tailored chat experience. @@ -293,6 +361,8 @@ import { CometChatMessageList, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -359,9 +429,39 @@ return ( To learn more about such attributes, refer to the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). +#### Message Options (Long Press) + +To style the action sheet that appears when long-pressing a message, use `messageOptionsStyles` within `messageListStyles`: + +```javascript + + {/* Components */} + +``` + + + +`messageOptionsStyles` is separate from the top-level `actionSheetStyle`. The top-level `actionSheetStyle` applies to attachment options and other standalone action sheets, while `messageOptionsStyles` specifically styles the message long-press options. + + + ### Message Composer -The `CometChatMessageComposer` Component enables users to compose and send messages, including text, attachments, and stickers. This highly interactive component supports customization of input box styles, button appearances, and interaction feedback, ensuring it blends seamlessly with your app’s chat UI. +The `CometChatMessageComposer` component enables users to compose and send messages, including text, attachments, and stickers. This highly interactive component supports customization of input box styles, button appearances, and interaction feedback, ensuring it blends seamlessly with your app's chat UI. @@ -373,6 +473,8 @@ import { CometChatMessageComposer, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -451,7 +553,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Group Members -The `CometChatGroupMembers` Component lists participants in a chat group with details like names, avatars, and roles (e.g., admin or member). It supports customizable styles for list items, fonts, and background colors, ensuring it integrates with your app's group management interface. +The `CometChatGroupMembers` component lists participants in a chat group with details like names, avatars, and roles (e.g., admin or member). It supports customizable styles for list items, fonts, and background colors, ensuring it integrates with your app's group management interface. @@ -463,6 +565,8 @@ import { CometChatGroupMembers, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -530,7 +634,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Thread Header -The `CometChatThreadHeader` is used in threaded message views, displaying information about the parent message and its context. It provides a seamless way to navigate between the thread and the main conversation while maintaining context. +The `CometChatThreadHeader` component is used in threaded message views, displaying information about the parent message and its context. It provides a seamless way to navigate between the thread and the main conversation while maintaining context. @@ -545,6 +649,8 @@ import { CometChatThemeProvider, CometChatThreadHeader, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -643,7 +749,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Call Logs -The `CometChatCallLogs` Component provides a list of recent calls (voice or video), showing details like call type, duration, participants, and timestamps. Developers can style text, icons, and background elements, making it easy to match the app’s design system. +The `CometChatCallLogs` component provides a list of recent calls (voice or video), showing details like call type, duration, participants, and timestamps. Developers can style text, icons, and background elements, making it easy to match the app's design system. @@ -654,6 +760,8 @@ import { CometChatCallLogs, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -720,6 +828,8 @@ import { CometChatIncomingCall, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -794,6 +904,8 @@ import { CometChatMessageHeader, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -865,7 +977,7 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Call Button -The `CometChatCallButton` Component initiates voice or video calls with a single click. It supports various customization options for button color and icon styles, making it adaptable to different screen layouts and themes. These components further enhance the versatility of CometChat UIKit, ensuring that all aspects of messaging and calling functionality are cohesive, user-friendly, and fully customizable. +The `CometChatCallButton` component initiates voice or video calls with a single click. It supports various customization options for button color and icon styles, making it adaptable to different screen layouts and themes. These components further enhance the versatility of CometChat UIKit, ensuring that all aspects of messaging and calling functionality are cohesive, user-friendly, and fully customizable. @@ -876,6 +988,8 @@ import { CometChatCallButtons, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1000,12 +1115,11 @@ return ( To learn more about such attributes, refer to the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). - -## Base Component +## Base Components ### Avatar -The `CometChatAvatar` Component is used across the UIKit to represent users, groups, or placeholders visually. This highly reusable component supports various shapes (circle or square), sizes, borders, and fallback icons, allowing complete design consistency for profile or group images. +The `CometChatAvatar` component is used across the UIKit to represent users, groups, or placeholders visually. This highly reusable component supports various shapes (circle or square), sizes, borders, and fallback icons, allowing complete design consistency for profile or group images. @@ -1016,6 +1130,8 @@ import { CometChatAvatar, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1062,6 +1178,8 @@ import { CometChatStatusIndicator, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1109,6 +1227,8 @@ import { CometChatBadge, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1147,6 +1267,8 @@ import { CometChatDate, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1189,6 +1311,8 @@ import { CometChatReceipt, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1230,6 +1354,8 @@ import { CometChatMediaRecorder, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1299,6 +1425,8 @@ import { CometChatReactionList, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1344,6 +1472,8 @@ import { CometChatMessageInformation, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1389,13 +1519,15 @@ To learn more about such attributes, refer to the [theme interface](https://gith ### Bottom Sheet -The `CometChatBottomSheet` component is a wrapper around the React Native Modal that provides a bottom sheet experience. While the Modal component offers basic functionality for displaying content in a popup overlay, the CometChatBottomSheet enhances this by offering features like smooth slide-in animations and a background overlay. It picks up most of its styling from the theme, ensuring a consistent design with minimal configuration. This component simplifies the implementation of bottom sheet interactions. +The `CometChatBottomSheet` component is a wrapper around the React Native Modal that provides a bottom sheet experience. While the Modal component offers basic functionality for displaying content in a popup overlay, `CometChatBottomSheet` enhances this by offering features like smooth slide-in animations and a background overlay. It picks up most of its styling from the theme, ensuring a consistent design with minimal configuration. This component simplifies the implementation of bottom sheet interactions. ```javascript import { CometChatBottomSheet, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1487,6 +1621,8 @@ import { CometChatMessageComposer, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; + //code return ( @@ -1565,3 +1701,22 @@ return ( ``` To learn more about such attributes, refer to the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). + +--- + +## Next Steps + + + + Learn how CometChatThemeProvider manages light and dark modes + + + Customize primary, neutral, alert, and other color tokens + + + Style individual message bubbles and their content + + + Explore all available UI Kit components + + diff --git a/ui-kit/react-native/components-overview.mdx b/ui-kit/react-native/components-overview.mdx index 3a9154051..bf6957326 100644 --- a/ui-kit/react-native/components-overview.mdx +++ b/ui-kit/react-native/components-overview.mdx @@ -1,50 +1,163 @@ --- title: "Overview" +description: "Browse all prebuilt UI components in the CometChat React Native UI Kit — conversations, messages, users, groups, calls, and AI." --- -CometChat's **UI Kit** is a set of pre-built UI components that allows you to easily craft an in-app chat with all the essential messaging features. + -## Type of Components +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Required setup | `CometChatUIKit.init()` + `CometChatUIKit.login()` before rendering any component | +| Callback actions | `on={(param) => {}}` (e.g., `onItemPress`) | +| Data filtering | `RequestBuilder={new CometChat.RequestBuilder()}` | +| Toggle features | `hide={true}` or `Visibility={false}` | +| Custom rendering | `View={() => JSX}` (PascalCase) | +| Style overrides | `style={{ containerStyle: {}, itemStyle: {} }}` | +| Calling | Requires separate `@cometchat/calls-sdk-react-native` package | -UI components based on the behaviour and functionality can be categorized into three types: Base Components, Components, and Composite Components. + -### Base Components +## Architecture -Base Components form the building blocks of your app's user interface (UI). They focus solely on presenting visual elements based on input data, without handling any business logic. These components provide the foundational appearance and behavior for your UI. +The UI Kit is a set of independent components that compose into chat layouts. A typical two-panel layout uses four core components: -### Components +- **CometChatConversations** — sidebar listing recent conversations (users and groups) +- **CometChatMessageHeader** — toolbar showing avatar, name, online status, and typing indicator +- **CometChatMessageList** — scrollable message feed with reactions, receipts, and threads +- **CometChatMessageComposer** — rich text input with attachments, mentions, and voice notes -Components build upon Base Components by incorporating business logic. They not only render UI elements but also manage data loading, execute specific actions, and respond to events. This combination of visual presentation and functional capabilities makes Components essential for creating dynamic and interactive UIs. +Data flow: selecting a conversation in CometChatConversations yields a `CometChat.Conversation` object. Extract the `User` or `Group` via `getConversationWith()` and pass it as a prop to CometChatMessageHeader, CometChatMessageList, and CometChatMessageComposer. -### Composite Components +Components communicate through a publish/subscribe event bus (`CometChatUIEventHandler`). A component emits events that other components or application code can subscribe to without direct references. See [Events](/ui-kit/react-native/events) for the full list. -Composite Components are advanced UI elements that combine multiple Components or other Composite Components to achieve complex functionality. By layering components together, Composite Components offer a sophisticated and flexible approach to designing UIs. They enable diverse functionalities and interactions, making them versatile tools for creating rich user experiences. +Each component accepts callback props (`on`), view slot props (`View`) for replacing UI sections, `RequestBuilder` props for data filtering, and `style` props for customization. -## Actions +--- + +## Component Catalog + +All components are imported from `@cometchat/chat-uikit-react-native`. + +### Conversations and Lists + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatConversations | Scrollable list of recent conversations | `conversationsRequestBuilder`, `onItemPress`, `onError` | [Conversations](/ui-kit/react-native/conversations) | +| CometChatUsers | Scrollable list of users | `usersRequestBuilder`, `onItemPress`, `onError` | [Users](/ui-kit/react-native/users) | +| CometChatGroups | Scrollable list of groups | `groupsRequestBuilder`, `onItemPress`, `onError` | [Groups](/ui-kit/react-native/groups) | +| CometChatGroupMembers | Scrollable list of group members | `group`, `groupMemberRequestBuilder`, `onItemPress` | [Group Members](/ui-kit/react-native/group-members) | + +### Messages + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatMessageHeader | Toolbar with avatar, name, status, typing indicator | `user`, `group`, `showBackButton` | [Message Header](/ui-kit/react-native/message-header) | +| CometChatMessageList | Scrollable message list with reactions, receipts, threads | `user`, `group`, `messageRequestBuilder`, `goToMessageId` | [Message List](/ui-kit/react-native/message-list) | +| CometChatMessageComposer | Rich text input with attachments, mentions, voice notes | `user`, `group`, `onSendButtonPress`, `placeholderText` | [Message Composer](/ui-kit/react-native/message-composer) | +| CometChatThreadHeader | Parent message bubble and reply count for threaded view | `parentMessage`, `onClose` | [Thread Header](/ui-kit/react-native/threaded-messages-header) | + +### Calling + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatCallButtons | Voice and video call initiation buttons | `user`, `group`, `onVoiceCallPress`, `onVideoCallPress` | [Call Buttons](/ui-kit/react-native/call-buttons) | +| CometChatIncomingCall | Incoming call notification with accept/decline | `call`, `onAccept`, `onDecline` | [Incoming Call](/ui-kit/react-native/incoming-call) | +| CometChatOutgoingCall | Outgoing call screen with cancel control | `call`, `onClosePress` | [Outgoing Call](/ui-kit/react-native/outgoing-call) | +| CometChatCallLogs | Scrollable list of call history | `callLogsRequestBuilder`, `onItemPress` | [Call Logs](/ui-kit/react-native/call-logs) | + +### AI + +| Component | Purpose | Key Props | Page | +| --- | --- | --- | --- | +| CometChatAIAssistantChatHistory | AI assistant conversation history | `user`, `onMessageClicked`, `onNewChatButtonClick` | [AI Assistant Chat History](/ui-kit/react-native/ai-assistant-chat-history) | + +--- + +## Component API Pattern -Actions direct the operational behavior of a component. They are split into two categories: Predefined Actions and User-Defined Actions. +All components share a consistent API surface. -### Predefined Actions +### Actions -These are actions that are inherently programmed into a UI component. They are ingrained in the component itself by default, and they execute automatically in response to user interaction,without needing any additional user input. +Actions control component behavior. They split into two categories: -### User-Defined Actions +**Predefined Actions** are built into the component and execute automatically on user interaction (e.g., tapping send dispatches the message). No configuration needed. -These are actions that must be explicitly specified by the user. They are not innately part of the component like predefined actions. Instead, they must be developed based on the unique needsof the user or the application. User-defined actions provide adaptability and allow for the creation of custom behaviors that align with the individual needs of the application. +**User-Defined Actions** are callback props that fire on specific events. Override them to customize behavior: -To customize the behavior of a component, actions must be overridden by the user. This provides the user with control over how the component responds to specific events or interactions. +```tsx lines + openThreadPanel(message)} + onError={(error) => logError(error)} +/> +``` -Both Components and Composite Components expose actions to the user, which means that users can interact with these types of components through predefined or user-defined actions. On the otherhand, Base Components do not expose actions to the user as they are the foundational buildingblocks mainly responsible for rendering the user interface and do not carry any business logic oractions. +### Events -## Events +Events enable decoupled communication between components. A component emits events that other parts of the application can subscribe to without direct references. -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +```tsx lines +import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; -Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. +useEffect(() => { + const listenerId = "MESSAGE_LISTENER_" + Date.now(); + + CometChatUIEventHandler.addMessageListener(listenerId, { + ccMessageSent: ({ message }) => { + console.log("Message sent:", message); + }, + }); -## Configurations + return () => { + CometChatUIEventHandler.removeMessageListener(listenerId); + }; +}, []); +``` -Configurations offer the ability to customize the properties of each individual component within a Composite Component. If a Composite Component includes multiple components, each of these components will have its own set of properties that can be configured. This means multiple sets of configurations are available, one for each constituent component. This allows for fine-tuned customization of the Composite Component, enabling you to tailor its behavior and appearance to match specific requirements in a granular manner. +Each component page documents its emitted events in the Events section. + +### Filters + +List-based components accept `RequestBuilder` props to control which data loads: + +```tsx lines + +``` + +### Custom View Slots + +Components expose named view slots (PascalCase) to replace sections of the default UI: + +```tsx lines + } + SubtitleView={(user, group) => } + LeadingView={(user, group) => } +/> +``` + +### Style Overrides + +Every component accepts a `style` prop for customization: + +```tsx lines + +``` @@ -58,8 +171,25 @@ For these icons, only the following imageStyle properties are supported: Any extra properties provided in imageStyle will be ignored for default icons. -For custom icons, you can provide either JSX components or an ImageSourcePropType. JSX Components: These are rendered as-is, and no additional styles are applied. - -ImageSourcePropType (e.g., PNG, JPEG): The entire imageStyle passed will be applied to the image as expected. +For custom icons, you can provide either JSX components or an ImageSourcePropType. JSX Components are rendered as-is with no additional styles applied. ImageSourcePropType (e.g., PNG, JPEG) will have the entire imageStyle applied as expected. + +--- + +## Next Steps + + + + Chat features included out of the box + + + Customize colors, fonts, and styles + + + Add-on features like polls, stickers, and translation + + + Initialize, authenticate, and send messages + + \ No newline at end of file diff --git a/ui-kit/react-native/conversations.mdx b/ui-kit/react-native/conversations.mdx index 8e3f5f79d..839a0198d 100644 --- a/ui-kit/react-native/conversations.mdx +++ b/ui-kit/react-native/conversations.mdx @@ -1,1195 +1,1332 @@ --- title: "Conversations" +description: "Scrollable list of recent one-on-one and group conversations for the logged-in user." --- + +```json +{ + "component": "CometChatConversations", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatConversations } from \"@cometchat/chat-uikit-react-native\";", + "description": "Scrollable list of recent one-on-one and group conversations for the logged-in user.", + "primaryOutput": { + "prop": "onItemPress", + "type": "(conversation: CometChat.Conversation) => void" + }, + "props": { + "data": { + "conversationsRequestBuilder": { + "type": "CometChat.ConversationsRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "datePattern": { + "type": "(conversation: CometChat.Conversation) => string", + "note": "Custom function to format conversation timestamps" + } + }, + "callbacks": { + "onItemPress": "(conversation: CometChat.Conversation) => void", + "onItemLongPress": "(conversation: CometChat.Conversation) => void", + "onBack": "() => void", + "onSelection": "(conversations: Array) => void", + "onError": "(error: CometChat.CometChatException) => void", + "onEmpty": "() => void", + "onLoad": "(list: CometChat.Conversation[]) => void", + "onSearchBarClicked": "() => void", + "onSearchTextChanged": "(searchText: string) => void", + "onSubmit": "(conversations: Array) => void" + }, + "visibility": { + "hideBackButton": { "type": "boolean", "default": true }, + "hideHeader": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "receiptsVisibility": { "type": "boolean", "default": true }, + "hideSubmitButton": { "type": "boolean", "default": true }, + "usersStatusVisibility": { "type": "boolean", "default": true }, + "groupTypeVisibility": { "type": "boolean", "default": true }, + "deleteConversationOptionVisibility": { "type": "boolean", "default": true }, + "showSearchBar": { "type": "boolean", "default": false }, + "searchText": { "type": "string", "default": "\"\"" } + }, + "sound": { + "disableSoundForMessages": { "type": "boolean", "default": false }, + "customSoundForMessages": { "type": "audio source", "default": "built-in" } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["single", "multiple", "none"], + "default": "none" + } + }, + "viewSlots": { + "ItemView": "(conversation: CometChat.Conversation) => JSX.Element", + "LeadingView": "(conversation: CometChat.Conversation) => JSX.Element", + "TitleView": "(conversation: CometChat.Conversation) => JSX.Element", + "SubtitleView": "(conversation: CometChat.Conversation) => JSX.Element", + "TrailingView": "(conversation: CometChat.Conversation) => JSX.Element", + "LoadingView": "() => JSX.Element", + "EmptyView": "() => JSX.Element", + "ErrorView": "() => JSX.Element", + "AppBarOptions": "() => JSX.Element", + "SearchView": "() => JSX.Element" + }, + "formatting": { + "textFormatters": { + "type": "CometChatTextFormatter[]", + "default": "default formatters from data source" + } + } + }, + "events": [ + { + "name": "ccConversationDeleted", + "payload": "CometChat.Conversation", + "description": "Conversation deleted from list" + } + ], + "sdkListeners": [ + "onTextMessageReceived", + "onMediaMessageReceived", + "onCustomMessageReceived", + "onTypingStarted", + "onTypingEnded", + "onMessagesDelivered", + "onMessagesRead", + "onUserOnline", + "onUserOffline", + "onGroupMemberJoined", + "onGroupMemberLeft", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup" + ], + "compositionExample": { + "description": "Navigation-based conversations wired to message view", + "components": [ + "CometChatConversations", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemPress emits CometChat.Conversation -> extract User/Group via getConversationWith() -> navigate to Messages screen with user or group prop" + }, + "types": { + "SelectionMode": { + "single": "Select one conversation at a time", + "multiple": "Select multiple conversations", + "none": "No selection mode" + } + } +} +``` + + +## Where It Fits -## Overview +`CometChatConversations` is a sidebar list component. It renders recent conversations and emits the selected `CometChat.Conversation` via `onItemPress`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a standard chat layout. -`CometChatConversations` is a component that displays all conversations associated with the currently logged-in user. +```tsx lines +import { useState } from "react"; +import { View, Text, StyleSheet } from "react-native"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { + CometChatConversations, + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatThemeProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function ChatApp() { + const [selectedUser, setSelectedUser] = useState(); + const [selectedGroup, setSelectedGroup] = useState(); + + const handleItemPress = (conversation: CometChat.Conversation) => { + const entity = conversation.getConversationWith(); + if (entity instanceof CometChat.User) { + setSelectedUser(entity); + setSelectedGroup(undefined); + } else if (entity instanceof CometChat.Group) { + setSelectedGroup(entity); + setSelectedUser(undefined); + } + }; + + return ( + + + + + + + + {selectedUser || selectedGroup ? ( + + + + + + ) : ( + + Select a conversation + + )} + + + + + ); +} + +const styles = StyleSheet.create({ + container: { flex: 1, flexDirection: "row" }, + sidebar: { width: 350 }, + chatArea: { flex: 1 }, + placeholder: { flex: 1, justifyContent: "center", alignItems: "center" }, +}); +``` -## Usage - -### Integration +--- -To use Conversations in your component, use the following code snippet: +## Minimal Render -```tsx App.tsx +```tsx lines import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code -return ; -``` -### Actions +function ConversationsDemo() { + return ; +} -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +export default ConversationsDemo; +``` -##### onItemPress +--- -Function executed when an item is long-pressed in the conversation list, commonly used to initiate actions like delete, selection, or entering multi-select mode. +## Filtering Conversations - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +Pass a `CometChat.ConversationsRequestBuilder` to `conversationsRequestBuilder`. Pass the builder instance — not the result of `.build()`. -const onPressHandler = (conversationClicked: CometChat.Conversation) => { - //code -}; +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -return ; +function FilteredConversations() { + return ( + + ); +} ``` - +### Filter Recipes - +| Recipe | Code | +| --- | --- | +| Only user conversations | `new CometChat.ConversationsRequestBuilder().setConversationType("user")` | +| Only group conversations | `new CometChat.ConversationsRequestBuilder().setConversationType("group")` | +| Limit to 10 per page | `new CometChat.ConversationsRequestBuilder().setLimit(10)` | +| With specific tags | `new CometChat.ConversationsRequestBuilder().setTags(["vip"])` | +| Filter by user tags | `new CometChat.ConversationsRequestBuilder().withUserAndGroupTags(true).setUserTags(["premium"])` | +| Filter by group tags | `new CometChat.ConversationsRequestBuilder().withUserAndGroupTags(true).setGroupTags(["support"])` | -*** +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. -##### onItemLongPress +Refer to [ConversationRequestBuilder](/sdk/react-native/retrieve-conversations) for the full builder API. -Function executed when a conversation item is long-pressed, allowing additional actions like delete or select. +--- - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +## Actions and Events -const onLongPressHandler = (conversationClicked: CometChat.Conversation) => { - //code -}; +### Callback Props -return ; -``` +#### onItemPress - +Fires when a conversation row is tapped. Primary navigation hook — set the active conversation and render the message view. - +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -*** +function ConversationsWithPress() { + const handleItemPress = (conversation: CometChat.Conversation) => { + console.log("Selected:", conversation.getConversationId()); + }; -##### onBack + return ; +} +``` + +#### onItemLongPress -`onBack` is triggered when you press the back button in the app bar. It does not have a default behavior. However, you can override its behavior using the following code snippet. +Fires when a conversation item is long-pressed, allowing additional actions like delete or select. - - -```tsx +```tsx lines import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onBackHandler = () => { - //code -}; +function ConversationsWithLongPress() { + const handleLongPress = (conversation: CometChat.Conversation) => { + console.log("Long pressed:", conversation.getConversationId()); + }; -return ; + return ; +} ``` - +#### onSelection - +Fires when conversations are selected/deselected in selection mode. Requires `selectionMode` to be set. -*** +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -##### onSelection +function ConversationsWithSelection() { + const handleSelection = (conversations: Array) => { + console.log("Selected:", conversations.length); + }; -Called when a item from the fetched list is selected useful for multi-selection features. + return ( + + ); +} +``` - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +#### onError -const onSelectionHandler = (selection: Array) => { - //code -}; +Fires on internal errors (network failure, auth issue, SDK exception). -return ( - -); +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function ConversationsWithErrorHandler() { + return ( + { + console.error("CometChatConversations error:", error); + }} + /> + ); +} ``` - +#### onEmpty - +Fires when the conversation list is empty. -*** +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -##### OnError +function ConversationsWithEmptyHandler() { + return ( + console.log("No conversations")} + /> + ); +} +``` + +#### onLoad -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Conversations component. +Fires when the list is successfully fetched and loaded. - - -```tsx +```tsx lines import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onErrorHandler = (error: CometChat.CometChatException) => { - console.log("Error"); -}; +function ConversationsWithLoadHandler() { + const handleLoad = (list: CometChat.Conversation[]) => { + console.log("Conversations loaded:", list.length); + }; -return ; + return ; +} ``` - +### Global UI Events - +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Subscribe in a `useEffect` and unsubscribe on cleanup. -*** +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccConversationDeleted` | A conversation is deleted from the list | `CometChat.Conversation` | -##### onEmpty +When to use: sync external UI with conversation state changes. For example, update an unread count badge in a tab bar when a conversation is deleted, or remove a conversation from a custom sidebar. -Called when the list is empty, enabling custom handling such as showing a placeholder message - - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +```tsx lines +import { useEffect } from "react"; +import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onEmptyHandler = () => { - console.log("Empty"); -}; +function useConversationEvents() { + useEffect(() => { + const listenerId = "CONVERSATION_EVENTS_" + Date.now(); + + CometChatUIEventHandler.addConversationListener(listenerId, { + ccConversationDeleted: (conversation: CometChat.Conversation) => { + console.log("Deleted:", conversation.getConversationId()); + }, + }); -return ; + return () => { + CometChatUIEventHandler.removeConversationListener(listenerId); + }; + }, []); +} ``` - +### SDK Events (Real-Time, Automatic) - +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -*** +| SDK Listener | Internal behavior | +| --- | --- | +| `onTextMessageReceived` / `onMediaMessageReceived` / `onCustomMessageReceived` | Moves conversation to top, updates last message preview and unread count | +| `onTypingStarted` / `onTypingEnded` | Shows/hides typing indicator in the subtitle | +| `onMessagesDelivered` / `onMessagesRead` | Updates receipt ticks (unless `receiptsVisibility={false}`) | +| `onUserOnline` / `onUserOffline` | Updates online/offline status dot (unless `usersStatusVisibility={false}`) | +| `onGroupMemberJoined` / `onGroupMemberLeft` / `onGroupMemberKicked` / `onGroupMemberBanned` / `onMemberAddedToGroup` | Updates group conversation metadata | -##### onLoad +Automatic: new messages, typing indicators, receipts, user presence, group membership changes. -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Manual: deleting a conversation via the SDK directly (not through the component's context menu) requires emitting `ccConversationDeleted` for the UI to update. - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +--- -const onLoadHandler = () => { - console.log("Loading"); -}; +## Custom View Slots -return ; -``` +Each slot replaces a section of the default UI. Slots that accept a conversation parameter receive the `CometChat.Conversation` object for that row. - +| Slot | Signature | Replaces | +| --- | --- | --- | +| `ItemView` | `(conversation: CometChat.Conversation) => JSX.Element` | Entire list item row | +| `LeadingView` | `(conversation: CometChat.Conversation) => JSX.Element` | Avatar / left section | +| `TitleView` | `(conversation: CometChat.Conversation) => JSX.Element` | Name / title text | +| `SubtitleView` | `(conversation: CometChat.Conversation) => JSX.Element` | Last message preview | +| `TrailingView` | `(conversation: CometChat.Conversation) => JSX.Element` | Timestamp / badge / right section | +| `LoadingView` | `() => JSX.Element` | Loading spinner | +| `EmptyView` | `() => JSX.Element` | Empty state | +| `ErrorView` | `() => JSX.Element` | Error state | +| `AppBarOptions` | `() => JSX.Element` | Header bar options | +| `SearchView` | `() => JSX.Element` | Search bar | - +### ItemView -*** +Replace the entire list item row. -##### onSubmit + + + -Called when submit selection button is pressed. +```tsx lines +import { + CometChatConversations, + CometChatAvatar, + useTheme, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text } from "react-native"; - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +function CustomItemViewConversations() { + const theme = useTheme(); -const onSubmitHandler = (list:Array) => { - console.log('Submit', list); -}; + const getItemView = (conversation: CometChat.Conversation) => { + const conversationWith = conversation.getConversationWith(); + return ( + + + + {conversationWith.getName()} + + + ); + }; -return ; + return ; +} ``` - +### LeadingView + +Replace the avatar / left section. + + + + - +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text } from "react-native"; -*** +function LeadingViewConversations() { + const getLeadingView = (conversation: CometChat.Conversation) => { + const entity = conversation.getConversationWith(); + return ( + + + {entity.getName().charAt(0)} + + + ); + }; -### Filters + return ; +} +``` -You can set `ConversationsRequestBuilder` in the Conversations Component to filter the conversation list. You can modify the builder as per your specific requirements with multiple options available to know more refer to [ConversationRequestBuilder](/sdk/react-native/retrieve-conversations). +### TrailingView -You can set filters using the following parameters. +Replace the timestamp / badge / right section. -1. **Conversation Type:** Filters on type of Conversation, `User` or `Groups` -2. **Limit:** Number of conversations fetched in a single request. -3. **WithTags:** Filter on fetching conversations containing tags -4. **Tags:** Filters on specific `Tag` -5. **UserTags:** Filters on specific User `Tag` -6. **GroupTags:** Filters on specific Group `Tag` + + + - - -```tsx +```tsx lines import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text } from "react-native"; -const conversationsRequestBuilder = new CometChat.ConversationsRequestBuilder(); -conversationsRequestBuilder.setLimit(30); +function TrailingViewConversations() { + const getTrailingView = (conversation: CometChat.Conversation) => { + const unreadCount = conversation.getUnreadMessageCount(); + if (unreadCount === 0) return null; + + return ( + + + {unreadCount} + + + ); + }; -return ( - -); + return ; +} ``` - +### TitleView - +Replace the name / title text. -*** +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text } from "react-native"; -### Events +function TitleViewConversations() { + const getTitleView = (conversation: CometChat.Conversation) => { + const entity = conversation.getConversationWith(); + const isUser = entity instanceof CometChat.User; + + return ( + + + {entity.getName()} + + {isUser && (entity as CometChat.User).getStatus() === "online" && ( + + )} + + ); + }; -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. + return ; +} +``` -##### 1. ConversationDeleted +### SubtitleView -This event will be emitted when the user deletes a conversation +Replace the last message preview text. - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; + + + -CometChatUIEventHandler.addConversationListener("SOME_UNIQUE_ID", { - ccConversationDeleted: (conversation: CometChat.Conversation) => { - //code - }, -}); +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { Text } from "react-native"; -return { - /* your view*/ -}; +function SubtitleViewConversations() { + const getSubtitleView = (conversation: CometChat.Conversation) => { + const conversationWith = conversation.getConversationWith(); + if (conversationWith instanceof CometChat.User) { + return ( + + Last Active: {new Date(conversationWith.getLastActiveAt() * 1000).toLocaleString()} + + ); + } else if (conversationWith instanceof CometChat.Group) { + return ( + + {conversationWith.getMembersCount()} members + + ); + } + return null; + }; + + return ; +} ``` - +### AppBarOptions - +Custom view for the header bar options. -*** + + + - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.removeListener("SOME_UNIQUE_ID"); +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { TouchableOpacity, Text } from "react-native"; + +function AppBarOptionsConversations() { + return ( + ( + console.log("Settings pressed")}> + Settings + + )} + /> + ); +} ``` - +### options - +Custom context menu actions for each conversation item. -## Customization + + + -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -### Style +function OptionsConversations() { + const getOptions = (conversation: CometChat.Conversation) => [ + { + text: "Delete", + onPress: () => console.log("Delete:", conversation.getConversationId()), + textStyle: { color: "red" }, + }, + { + text: "Mute", + onPress: () => console.log("Mute:", conversation.getConversationId()), + }, + ]; -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. + return ; +} +``` -##### Style +### addOptions -You can pass a styling object as a prop to the `CometChatConversations` component to customize its styling. +Extends the default context menu actions with additional options. - + - - -```tsx +```tsx lines import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code -return ( - -); -``` +import { CometChat } from "@cometchat/chat-sdk-react-native"; - +function AddOptionsConversations() { + const addOptions = (conversation: CometChat.Conversation) => [ + { + text: "Archive", + onPress: () => console.log("Archive:", conversation.getConversationId()), + }, + { + text: "Pin", + onPress: () => console.log("Pin:", conversation.getConversationId()), + }, + ]; - + return ; +} +``` -### Functionality +### datePattern -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +Custom date format for displaying timestamps. - + -Below is a list of customizations along with corresponding code snippets +```tsx lines +import { + CometChatConversations, + CometChatConversationUtils, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function DatePatternConversations() { + const generateDateString = (conversation: CometChat.Conversation) => { + const lastMessage = CometChatConversationUtils.getLastMessage(conversation); + const conversationWith = conversation.getConversationWith(); + const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + const timeStamp = lastMessage?.updatedAt || conversationWith.createdAt; + const date = new Date(timeStamp * 1000); + const day = days[date.getUTCDay()]; + const hours = date.getUTCHours(); + const minutes = String(date.getUTCMinutes()).padStart(2, "0"); + return `${day}, ${hours}:${minutes}`; + }; -| Property | Description | Code | -| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- | -| **hideBackButton** | Prop used to toggle the visibility of the back button in the app bar. | `hideBackButton={true}` | -| **hideHeader** | Prop used to toggle visibility for the toolbar/header bar | `hideHeader={true}` | -| **hideError** | Prop to hide error state on fetching conversations | `hideError={true}` | -| **receiptsVisibility** | Prop used to control the visibility of read receipts without affecting the functionality of marking messages as read and delivered | `receiptsVisibility={false}` | -| **selectionMode** | This method determines the selection mode for conversations, enabling users to select either a single conversation or multiple conversations at once. | `selectionMode="multiple"` | -| **hideSubmitButton** | Prop used to toggle the visibility of the submit button when selectionMode is enabled. | `hideSubmitButton={true}` | -| **usersStatusVisibility** | Prop used to toggle user status visibilty. | `usersStatusVisibility={false}` | -| **groupTypeVisibility** | Prop used to toggle group type visibilty. | `groupTypeVisibility={false}` | -| **deleteConversationOptionVisibility** | Prop used to toggle delete conversation option visibilty. | `deleteConversationOptionVisibility={false}` | + return ; +} +``` + +### textFormatters + +Custom text formatters for the conversation subtitle. + + + + -### Advanced +```tsx lines +import { + CometChatConversations, + CometChatTextFormatter, + CometChatMentionsFormatter, +} from "@cometchat/chat-uikit-react-native"; -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +function TextFormattersConversations() { + const getTextFormatters = () => { + const textFormatters: CometChatTextFormatter[] = []; + const mentionsFormatter = new CometChatMentionsFormatter(); + mentionsFormatter.setMentionsStyle({ + textStyle: { color: "#D6409F" }, + selfTextStyle: { color: "#30A46C" }, + }); + textFormatters.push(mentionsFormatter); + return textFormatters; + }; -*** + return ; +} +``` -#### disableSoundForMessages +See [CometChatMentionsFormatter](/ui-kit/react-native/mentions-formatter-guide) for mention formatting. -This method disables sound notifications for incoming messages. When activated, the application will not play an audio alert when new messages arrive. This feature is beneficial in scenarios where: +--- -* Users prefer a silent messaging experience -* The app is being used in a professional or quiet environment -* Background processes need to minimize distractions +## Common Patterns -By providing this option, the app allows users to tailor their notification preferences. +### Custom empty state with CTA - - -```tsx +```tsx lines import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code -return ( - -); +import { View, Text, TouchableOpacity } from "react-native"; + +function EmptyStateConversations() { + return ( + ( + + No conversations yet + console.log("Start conversation")}> + Start a conversation + + + )} + /> + ); +} ``` - +### Hide all chrome — minimal list - +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -*** +function MinimalConversations() { + return ( + + ); +} +``` -#### customSoundForMessages +### Conversations with search -This method enables users to personalize their chat experience by setting a custom sound file for incoming message notifications. Users can choose from: +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -* Default system sounds -* Custom sound files uploaded by the user -* Theme-based or brand-specific notification sounds +function SearchableConversations() { + return ( + console.log("Search:", text)} + /> + ); +} +``` -By allowing sound customization, this feature enhances personalization and improves user engagement. +### Multi-select with submit - - -```tsx +```tsx lines import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -import customMessageSound from "./customMessageSound.wav"; -//code -return ( - -); -``` +import { CometChat } from "@cometchat/chat-sdk-react-native"; - +function MultiSelectConversations() { + const handleSubmit = (conversations: Array) => { + console.log("Selected conversations:", conversations.length); + }; - + return ( + + ); +} +``` -*** +--- -#### LoadingView +## Styling -This method allows developers to set a custom loading view that is displayed when data is being fetched or loaded within the component. Instead of using a default loading spinner, a custom animation, progress bar, or branded loading screen can be displayed. +The component uses the theme system from `CometChatThemeProvider`. Pass a `style` prop to customize the appearance. -Use cases: + + + -* Showing a skeleton loader for conversations while data loads -* Displaying a custom progress indicator with branding -* Providing an animated loading experience for a more engaging UI +```tsx lines +import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code -const getLoadingView = (): JSX.Element => { - //your custom Loading View - //return jsx; -}; -return ( - -); +function StyledConversations() { + return ( + + ); +} ``` - +### Style Properties - +| Property | Type | Description | +| --- | --- | --- | +| `containerStyle` | `ViewStyle` | Style for the root container | +| `headerStyle` | `ViewStyle` | Style for the header section | +| `titleStyle` | `TextStyle` | Style for the header title | +| `itemStyle` | `object` | Style for list items (includes `avatarStyle`, `badgeStyle`, `titleStyle`, `subtitleStyle`) | +| `searchStyle` | `object` | Style for the search bar | -*** +--- -#### EmptyView +## Props -Configures a custom view to be displayed when there are no conversations or messages in the list. This improves the user experience by providing meaningful content instead of an empty screen. +All props are optional unless noted. -Examples: +### conversationsRequestBuilder -* Displaying a message like "No conversations yet. Start a new chat!" -* Showing an illustration or animation to make the UI visually appealing -* Providing a button to start a new conversation +Controls which conversations load and in what order. - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code -const getEmptyView = (): JSX.Element => { - //your custom Empty View - //return jsx; -}; -return ( - -); -``` +| | | +| --- | --- | +| Type | `CometChat.ConversationsRequestBuilder` | +| Default | SDK default (30 per page) | - +Pass the builder instance, not the result of `.build()`. - +--- -*** +### customSoundForMessages -#### ErrorView +Custom sound file for incoming message notifications. -Defines a custom error state view that appears when an issue occurs while loading conversations or messages. This enhances the user experience by displaying friendly error messages instead of generic system errors. +| | | +| --- | --- | +| Type | `audio source` | +| Default | Built-in sound | -Common use cases: +--- -* Showing "Something went wrong. Please try again." with a retry button -* Displaying a connection issue message if the user is offline -* Providing troubleshooting steps for the error +### datePattern - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code -const getErrorView = (): JSX.Element => { - //your custom Error View - //return jsx; -}; -return ( - -); -``` +Custom function to format conversation timestamps. - +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => string` | +| Default | Component default | - +--- -*** +### deleteConversationOptionVisibility -#### LeadingView +Shows/hides the delete option in the context menu. -Allows setting a custom leading view element that appears at the beginning of each conversation item. This is typically used to modify profile pictures, avatars, or icons in the conversation list. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -Examples: +--- -* Displaying user avatars with online/offline status indicators -* Using initials or custom graphics instead of images +### disableSoundForMessages - - - +Disables the notification sound for incoming messages. - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getLeadingView = (conversation: CometChat.Conversation): JSX.Element => { - //your custom Leading View - //return jsx; -}; -return ( - -); -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- - +### EmptyView -*** +Custom component displayed when there are no conversations. -#### TitleView +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in empty state | -Overrides the default title view in the conversation list with a custom layout. This is useful for branding or modifying how conversation names and details are displayed. +--- -Examples: +### ErrorView -* Displaying conversation titles with additional metadata (e.g., last seen time) -* Custom fonts or text styles for conversation names -* Adding icons or indicators next to titles +Custom component displayed when an error occurs. - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTitleView = (user: CometChat.Conversation): JSX.Element => { - //your custom Title View - //return jsx; -}; -return ( - -); -``` +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in error state | - +--- - +### groupTypeVisibility -Demonstration +Shows/hides the group type icon (public/private/password). - - - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -*** +--- -#### TrailingView +### hideBackButton -Customizes the trailing (end) view of a conversation item, which is typically used for action buttons or additional information. +Hides the back button in the header. -Examples: +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -* Adding a mute/unmute button for each conversation -* Displaying the last message time in a custom format -* Showing unread message counts or notification badges +--- - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTrailingView = (conversation: CometChat.Conversation): JSX.Element => { - //your custom Trailing View - //return jsx; -}; -return ( - -); -``` +### hideError - +Hides the error state view. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Demonstration +--- - - - +### hideHeader -*** +Hides the entire header bar. -#### ItemView +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -This function allows developers to assign a completely custom list item design to the Conversations Component, replacing the default layout. +--- -Use cases: +### hideSubmitButton -* Implementing a unique conversation list design with custom styling -* Adding extra elements like swipe gestures, priority indicators, or group labels -* Fully customizing how messages are displayed in the list +Hides the submit button when selection mode is enabled. - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getItemView = (conversation: CometChat.Conversation): JSX.Element => { - //your custom Item View - //return jsx; -}; -return ; -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | - +--- - +### ItemView -Demonstration +Custom renderer for the entire list item row. - - - +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in list item | - - -```tsx -import { - CometChatConversations, - CometChatDate, - CometChatAvatar, - CometChatStatusIndicator, - CometChatTheme, - useTheme, -} from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//other imports -const theme: CometChatTheme = useTheme(); -//code -const getItemView = (conversation: CometChat.Conversation): JSX.Element => { - const conversationWith = conversation.getConversationWith(); - return ( - - - - {conversationWith instanceof CometChat.User && ( - - )} - - - {conversationWith.getName()} - - {getDateView(conversation)} - - ); - }; +--- - const getDateView = (conversation: CometChat.Conversation) => { - const timestamp = conversation.getLastMessage()?.getSentAt(); - return ( - - ); - }; +### LeadingView -return ; -``` +Custom renderer for the avatar / left section. - +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in avatar | - +--- -*** +### LoadingView -#### TextFormatters +Custom component displayed during the loading state. -This method enables developers to define and apply text formatters that dynamically modify or transform message content before rendering it in the UI. Text formatters can be used for purposes such as: +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in loading indicator | -* Automatically converting URLs into clickable links -* Applying Markdown or rich text styling -* Replacing certain words or patterns with emojis or predefined text -* Censoring specific words for moderation +--- -By utilizing this method, developers can enhance readability, usability, and compliance with content guidelines. [MentionsFormatter Guide](/ui-kit/react-native/mentions-formatter-guide) +### onBack -**Example** +Callback fired when the back button is pressed. - - - +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | - - -```tsx -import { - CometChatConversations, - CometChatTextFormatter, - CometChatMentionsFormatter, -} from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTextFomatters = () => { - const textFormatters: CometChatTextFormatter[] = []; - const mentionsFormatter = new CometChatMentionsFormatter(); - mentionsFormatter.setMentionsStyle({ - textStyle: { - color: "#D6409F", - }, - selfTextStyle: { - color: "#30A46C", - }, - }); - textFormatters.push(mentionsFormatter); - return textFormatters; -}; -return ( - -); -``` +--- - +### onEmpty - +Callback fired when the conversation list is empty. -#### AppBarOptions +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -You can set Custom `AppBarOptions` to the `CometChatConversations` widget. +--- -Use Cases: +### onError -* Archive Chat -* Mark All as Read -* Delete Conversations +Callback fired when the component encounters an error. - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code -return ( - { - return ( - { - //do something - }} - > - Custom App Bar Options - - ); - }} - /> -); -``` +| | | +| --- | --- | +| Type | `(error: CometChat.CometChatException) => void` | +| Default | `undefined` | - +--- - +### onItemLongPress -Demonstration +Callback fired when a conversation row is long-pressed. - - - +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => void` | +| Default | `undefined` | -*** +--- -#### DatePattern +### onItemPress -This method customizes the date format used for displaying timestamps in conversations or chat components. Developers can specify formats such as: +Callback fired when a conversation row is tapped. -* dd/MM/yyyy HH:mm → Example: 10/07/2024 14:30 -* MMM dd, yyyy → Example: Jul 10, 2024 -* hh:mm a → Example: 02:30 PM +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => void` | +| Default | `undefined` | -Custom date patterns improve the localization and readability of time-sensitive messages, catering to different regional preferences. +--- - - -```tsx -import { - CometChatConversations, - CometChatConversationUtils, -} from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const generateDateString = (conversation: CometChat.Conversation) => { - const lastMessage: any = - CometChatConversationUtils.getLastMessage(conversation); - const conversationWith: any = conversation.getConversationWith(); - const days = [ - "Sunday", - "Monday", - "Tuesday", - "Wednesday", - "Thursday", - "Friday", - "Saturday", - ]; - const timeStamp = - (lastMessage && lastMessage["updatedAt"]) || - conversationWith["createdAt"] || - conversationWith["lastActiveAt"]; - let timeStampInSeconds = new Date(timeStamp * 1000); - const day = days[timeStampInSeconds.getUTCDay()].substring(0, 3); - const hours = timeStampInSeconds.getUTCHours(); - const minutes = String(timeStampInSeconds.getUTCMinutes()).padStart(2, "0"); - - return `${day}, ${hours}:${minutes}`; -}; - -return ( - -); -``` +### onLoad - +Callback fired when conversations are loaded. - +| | | +| --- | --- | +| Type | `(list: CometChat.Conversation[]) => void` | +| Default | `undefined` | -Demonstration +--- - - - +### onSearchBarClicked -#### SubtitleView +Callback fired when the search bar is clicked. Requires `showSearchBar={true}`. -The SubtitleView method allows developers to customize the subtitle view of each conversation item in the list. The subtitle typically displays additional information below the conversation title, such as the last message, message status, or other relevant details. +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -Use Cases: +--- -* Customizing the Last Message Display – Modify how the last message appears, including text styling, truncation, or emoji support. -* Message Status Indicators – Show message status (e.g., Sent, Delivered, Read) alongside the last message. -* Typing Indicators – Display "User is typing..." in real time. +### onSearchTextChanged - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code -const getSubtitleView = (conversation: CometChat.Conversation) => { - const conversationWith: any = conversation.getConversationWith(); - if (conversationWith instanceof CometChat.User) { - return ( - - Last Active at:{" "} - {conversationWith.getLastActiveAt() - ? formatTime(conversationWith.getLastActiveAt()) - : "--"} - - ); - } else if (conversationWith instanceof CometChat.Group) { - return ( - - Created at: {formatTime(conversationWith.getCreatedAt())} - - ); - } else { - return ( - - Click To View Chat - - ); - } -}; - -function formatTime(timestamp: number) { - const date = new Date(timestamp * 1000); - return date.toLocaleString("en-GB", { - hour12: false, - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - }); -} +Callback fired when search text changes. Requires `showSearchBar={true}`. -return ( - -); -``` +| | | +| --- | --- | +| Type | `(searchText: string) => void` | +| Default | `undefined` | - +--- - +### onSelection -Demonstration +Callback fired when conversations are selected/deselected. Requires `selectionMode` to be set. - - - +| | | +| --- | --- | +| Type | `(conversations: Array) => void` | +| Default | `undefined` | -#### options +--- -This method sets a predefined list of actions that users can perform when they long press a conversation in the list. These options typically include: +### onSubmit -Use Cases: +Callback fired when the submit button is pressed. Requires `selectionMode` to be set. -* Deleting a conversation -* Marking a conversation as read or unread -* Pinning or unpinning a conversation -* Muting notifications for a specific conversation +| | | +| --- | --- | +| Type | `(conversations: Array) => void` | +| Default | `undefined` | -By customizing these options, developers can provide a streamlined and contextually relevant user experience. +--- - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code +### receiptsVisibility -const setMyOptions = (_conversation: CometChat.Conversation) => { - return [ - //options - ]; - }; +Shows/hides message read/delivery receipt indicators. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -return ( - -); -``` +--- - +### SearchView - +Custom search bar component. -Demonstration +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in search bar | - - - +--- - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//import your delete icon +### selectionMode +Enables single or multi-select mode on list items. -//code -const setMyOptions = (_conversation: CometChat.Conversation) => { - return [ - { - text: "Delete", - onPress: () => { - - }, - icon: ( - - ), - textStyle: { color: theme.color.error }, - }, - ]; - }; +| | | +| --- | --- | +| Type | `"single" \| "multiple" \| "none"` | +| Default | `"none"` | -return ( - -); -``` +--- - +### searchText - +Current search text value for the search bar. -#### addOptions +| | | +| --- | --- | +| Type | `string` | +| Default | `""` | -This method extends the default set of actions triggered when a user long-presses a conversation item. Unlike setOptions, which replaces the existing options, addOptions allows developers to append additional actions while retaining the default ones. +--- -Use Cases: +### showSearchBar -* Adding a "Report Spam" action -* Introducing a "Save to Notes" option -* Integrating third-party actions such as "Share to Cloud Storage" +Shows a search bar at the top of the list. -This method provides flexibility in modifying user interaction capabilities. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//code +--- -const addOptions = (_conversation: CometChat.Conversation) => { - return [ - //options - ]; - }; +### SubtitleView +Custom renderer for the last message preview text. -return ( - -); -``` +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in subtitle | - +--- - +### textFormatters -Demonstration +Custom text formatters for the conversation subtitle. - - - +| | | +| --- | --- | +| Type | `CometChatTextFormatter[]` | +| Default | Default formatters from data source | - - -```tsx -import { CometChatConversations } from "@cometchat/chat-uikit-react-native"; -//import your icons +--- +### TitleView -//code -const addOptions = (_conversation: CometChat.Conversation) => { - return [ - { - text: "Archive", - onPress: () => { - - }, - icon: ( - - ), - textStyle: { color: theme.color.staticBlack }, - }, - { - text: "Pin", - onPress: () => { - - }, - icon: ( - - ), - textStyle: { color: theme.color.staticBlack }, - }, - { - text: "Mark as unread", - onPress: () => { - - }, - icon: ( - - ), - textStyle: { color: theme.color.staticBlack }, - }, +Custom renderer for the name / title text. - ]; - }; +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in title | +--- -return ( - -); -``` +### TrailingView + +Custom renderer for the timestamp / badge / right section. + +| | | +| --- | --- | +| Type | `(conversation: CometChat.Conversation) => JSX.Element` | +| Default | Built-in trailing view | - +--- + +### usersStatusVisibility + +Shows/hides the online/offline status indicator. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | + +--- - +## Next Steps + + + + Display the full chat interface after selecting a conversation + + + Display and interact with user lists + + + Display and manage group conversations + + + Customize the appearance of UI Kit components + + \ No newline at end of file diff --git a/ui-kit/react-native/core-features.mdx b/ui-kit/react-native/core-features.mdx index 3b15e4a03..bb4fcf7f7 100644 --- a/ui-kit/react-native/core-features.mdx +++ b/ui-kit/react-native/core-features.mdx @@ -1,12 +1,26 @@ --- title: "Core" +description: "Explore the core messaging features available in CometChat's React Native UI Kit, including instant messaging, media sharing, read receipts, typing indicators, and more." --- + +**Quick Reference for AI Agents & Developers** + +Key components powering core features: +- **Conversations** → [CometChatConversations](/ui-kit/react-native/conversations) +- **Message List** → [CometChatMessageList](/ui-kit/react-native/message-list) +- **Message Composer** → [CometChatMessageComposer](/ui-kit/react-native/message-composer) +- **Message Header** → [CometChatMessageHeader](/ui-kit/react-native/message-header) +- **Users** → [CometChatUsers](/ui-kit/react-native/users) +- **Groups** → [CometChatGroups](/ui-kit/react-native/groups) +- **Group Members** → [CometChatGroupMembers](/ui-kit/react-native/group-members) + + ## Overview The UI Kit comprises a variety of components, each designed to work seamlessly with one another to deliver a comprehensive and intuitive chat experience. -Here's how different UI Kit components work together to achieve CometChat's Core features: +Here's how different UI Kit components work together to achieve CometChat's core features: ## Instant Messaging @@ -31,14 +45,14 @@ Beyond text, CometChat allows users to share various media types within their co | Components | Functionality | | ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| [MessageComposer](/ui-kit/react-native/message-composer) | [MessageComposer](/ui-kit/react-native/message-composer) contains an ActionSheet component—a contextual menu overlay that provides multiple options for sharing media files. | +| [MessageComposer](/ui-kit/react-native/message-composer) | [MessageComposer](/ui-kit/react-native/message-composer) contains an ActionSheet component — a contextual menu overlay that provides multiple options for sharing media files. | | [MessageList](/ui-kit/react-native/message-list) | [MessageList](/ui-kit/react-native/message-list) component displays various media message bubbles, including [Image Bubble](/ui-kit/react-native/message-bubble-styling#image-bubble), [File Bubble](/ui-kit/react-native/message-bubble-styling#file-bubble), [Audio Bubble](/ui-kit/react-native/message-bubble-styling#audio-bubble), [Video Bubble](/ui-kit/react-native/message-bubble-styling#video-bubble) | -> A Message component can be built by combining three key components: [MessageHeader](/ui-kit/react-native/message-header), [MessageList](/ui-kit/react-native/message-list), and [MessageComposer](/ui-kit/react-native/message-composer). Together, they create a complete messaging interface. +> A complete messaging interface can be built by combining three key components: [MessageHeader](/ui-kit/react-native/message-header), [MessageList](/ui-kit/react-native/message-list), and [MessageComposer](/ui-kit/react-native/message-composer). ## Read Receipts -CometChat's Read Receipts feature provides visibility into the message status, letting users know when a message has been delivered and read. This brings clarity to the communication and ensures users are informed about the status of their messages. +CometChat's Read Receipts feature provides visibility into message status, letting users know when a message has been delivered and read. This brings clarity to communication and ensures users are informed about the status of their messages. @@ -46,13 +60,13 @@ CometChat's Read Receipts feature provides visibility into the message status, l | Components | Functionality | | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) component renders Conversations item List, Conversation item also displays the delivery status of the last message providing users with real-time updates on the status of their messages. | -| [MessageList](/ui-kit/react-native/message-list) | [MessageList](/ui-kit/react-native/message-list) component renders different types of Message bubbles, Read Recept status is an integral part of all message bubbles, no matter the type, and provides real-time updates about the status of the message. | +| [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) component renders a conversation item list. Each item also displays the delivery status of the last message, providing users with real-time updates on message status. | +| [MessageList](/ui-kit/react-native/message-list) | [MessageList](/ui-kit/react-native/message-list) component renders different types of message bubbles. Read receipt status is an integral part of all message bubbles, regardless of type, and provides real-time updates about message status. | | [MessageInformation](/ui-kit/react-native/component-styling#message-information) | [MessageInformation](/ui-kit/react-native/component-styling#message-information) component provides transparency into the status of each sent message, giving the sender insights into whether their message has been delivered and read. | ## Mark as Unread -Mark as Unread feature allows users to manually mark messages as unread, helping them keep track of important conversations they want to revisit later. When enabled, the message list can automatically start from the first unread message, making it easier to pick up where you left off. +The Mark as Unread feature allows users to manually mark messages as unread, helping them keep track of important conversations they want to revisit later. When enabled, the message list can automatically start from the first unread message, making it easier to pick up where you left off. @@ -65,7 +79,7 @@ Mark as Unread feature allows users to manually mark messages as unread, helping ## Typing Indicator -The Typing Indicator feature in CometChat shows when a user is typing a response in real-time, fostering a more interactive and engaging chat environment. This feature enhances the real-time communication experience, making conversations feel more natural and fluid. +The Typing Indicator feature shows when a user is typing a response in real-time, fostering a more interactive and engaging chat environment. This enhances the real-time communication experience, making conversations feel more natural and fluid. @@ -73,12 +87,12 @@ The Typing Indicator feature in CometChat shows when a user is typing a response | Components | Functionality | | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) component renders a list of conversation items, each displaying real-time typing indicators. This means that if a user in a one-on-one or group chat is currently typing, the status will be reflected instantly in the conversation list. | +| [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) component renders a list of conversation items, each displaying real-time typing indicators. If a user in a one-on-one or group chat is currently typing, the status is reflected instantly in the conversation list. | | [Message Header](/ui-kit/react-native/message-header) | [Message Header](/ui-kit/react-native/message-header) component displays user or group details in the toolbar. It also manages the typing indicator, dynamically updating to show a real-time "typing..." status when a user or group member is actively typing. | ## User Presence -CometChat’s User Presence feature lets users see the online or offline status of their contacts, helping them choose the right time to start a conversation and set expectations for response times. +CometChat's User Presence feature lets users see the online or offline status of their contacts, helping them choose the right time to start a conversation and set expectations for response times. @@ -87,13 +101,13 @@ CometChat’s User Presence feature lets users see the online or offline status | Components | Functionality | | --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) component renders a list of conversation items, each displaying user presence information such as online or offline status. | -| [MessageHeader](/ui-kit/react-native/message-header) | [Message Header](/ui-kit/react-native/message-header) component displays user or group details in the toolbar. It also handles user presence showing real-time online or offline status for the selected user. | +| [MessageHeader](/ui-kit/react-native/message-header) | [Message Header](/ui-kit/react-native/message-header) component displays user or group details in the toolbar. It also handles user presence, showing real-time online or offline status for the selected user. | | [Users](/ui-kit/react-native/users) | [Users](/ui-kit/react-native/users) component displays a list of users available in your app and is also responsible for showing their real-time presence status such as online or offline. | -| [GroupMembers](/ui-kit/react-native/group-members) | [Group Members](/ui-kit/react-native/group-members) component displays a list of users within a group and also manages real-time presence information showing whether each member is online or offline. | +| [GroupMembers](/ui-kit/react-native/group-members) | [Group Members](/ui-kit/react-native/group-members) component displays a list of users within a group and also manages real-time presence information, showing whether each member is online or offline. | ## Reactions -CometChat's Reactions feature adds a layer of expressiveness to your chat application by allowing users to react to messages. With Reactions, users can convey a range of emotions or express their thoughts on a particular message without typing out a full response, enhancing their user experience and fostering greater engagement. +CometChat's Reactions feature adds a layer of expressiveness to your chat application by allowing users to react to messages. With Reactions, users can convey a range of emotions or express their thoughts on a particular message without typing out a full response, enhancing the user experience and fostering greater engagement. @@ -105,7 +119,7 @@ CometChat's Reactions feature adds a layer of expressiveness to your chat applic ## Mentions -Mentions is a robust feature provided by CometChat that enhances the interactivity and clarity of group or 1-1 chats by allowing users to directly address or refer to specific individuals in a conversation. +Mentions is a feature that enhances the interactivity and clarity of group or 1-on-1 chats by allowing users to directly address or refer to specific individuals in a conversation. @@ -113,13 +127,13 @@ Mentions is a robust feature provided by CometChat that enhances the interactivi | Components | Functionality | | ------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) component enhances the user experience by integrating the Mentions feature, allowing users to see directly from the conversation list when they or others have been specifically mentioned in a chat. | +| [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) component integrates the Mentions feature, allowing users to see directly from the conversation list when they or others have been specifically mentioned in a chat. | | [MessageComposer](/ui-kit/react-native/message-composer) | [MessageComposer](/ui-kit/react-native/message-composer) component allows users to compose and send various types of messages, including support for the Mentions feature to directly address participants within the conversation. | | [MessageList](/ui-kit/react-native/message-list) | [MessageList](/ui-kit/react-native/message-list) component displays a list of sent and received messages. It also supports rendering Mentions, enhancing the clarity and interactivity of conversations by highlighting direct references to users. | ## Quoted Reply -Quoted Reply is a robust feature provided by CometChat that enables users to quickly reply to specific messages by selecting the "Reply" option from a message's action menu. This enhances context, keeps conversations organized, and improves overall chat experience in both 1-1 and group chats. +The Quoted Reply feature enables users to quickly reply to specific messages by selecting the "Reply" option from a message's action menu. This enhances context, keeps conversations organized, and improves the overall chat experience in both 1-on-1 and group chats. @@ -128,11 +142,11 @@ Quoted Reply is a robust feature provided by CometChat that enables users to qui | Components | Functionality | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [Message List](/ui-kit/react-native/message-list) | [Message List](/ui-kit/react-native/message-list) supports replying to messages via the "Reply" option. Users can select "Reply" on a message to open the composer with the quoted reply pre-filled, maintaining context. | -| [Message Composer](/ui-kit/react-native/message-composer) | [Message Composer](/ui-kit/react-native/message-composer) works seamlessly with Quoted Message by showing the quoted reply above the input field, letting users compose their response in proper context. | +| [Message Composer](/ui-kit/react-native/message-composer) | [Message Composer](/ui-kit/react-native/message-composer) works seamlessly with Quoted Reply by showing the quoted message above the input field, letting users compose their response in proper context. | ## Conversation and Advanced Search -Conversation and Advanced Search is a powerful feature provided by CometChat that enables users to quickly find conversations, messages, and media across chats in real time. It supports filters, scopes, and custom actions, allowing users to locate content efficiently while keeping the chat experience smooth and intuitive. +Conversation and Advanced Search enables users to quickly find conversations, messages, and media across chats in real time. It supports filters, scopes, and custom actions, allowing users to locate content efficiently while keeping the chat experience smooth and intuitive. @@ -140,7 +154,7 @@ Conversation and Advanced Search is a powerful feature provided by CometChat tha | Components | Functionality | | ------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| [Search](/ui-kit/react-native/search) | [Search](/ui-kit/react-native/search) allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | +| Search | Search allows users to search across conversations and messages in real time. Users can click on a result to open the conversation or jump directly to a specific message. | | [Message Header](/ui-kit/react-native/message-header) | [Message Header](/ui-kit/react-native/message-header) shows the search button in the chat header, allowing users to search within a conversation. | | [Message List](/ui-kit/react-native/message-list) | [Message List](/ui-kit/react-native/message-list) shows the selected message when clicked from search results and highlights it in the message list. | | [Conversations](/ui-kit/react-native/conversations) | [Conversations](/ui-kit/react-native/conversations) displays the search input. | @@ -201,4 +215,23 @@ CometChat facilitates Group Chats, allowing users to have conversations with mul -For a comprehensive understanding and guide on implementing and using the Groups feature in CometChat, you should refer to our detailed guide on [Groups](/ui-kit/react-native/groups). +For a comprehensive understanding and guide on implementing and using the Groups feature in CometChat, refer to the detailed guide on [Groups](/ui-kit/react-native/groups). + +--- + +## Next Steps + + + + Explore voice and video calling capabilities + + + Add stickers, polls, link previews, and more + + + Browse all available UI Kit components + + + Customize colors, fonts, and appearance + + diff --git a/ui-kit/react-native/custom-text-formatter-guide.mdx b/ui-kit/react-native/custom-text-formatter-guide.mdx new file mode 100644 index 000000000..bada65afe --- /dev/null +++ b/ui-kit/react-native/custom-text-formatter-guide.mdx @@ -0,0 +1,331 @@ +--- +title: "Custom Text Formatter" +description: "Extend the CometChatTextFormatter base class to implement custom inline text patterns with regex and callbacks in React Native." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key class | `CometChatTextFormatter` (abstract base class for custom formatters) | +| Required setup | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Extend to create custom inline text patterns with regex, styling, and callbacks | +| Features | Text formatting, customizable styles, dynamic text replacement, suggestion list integration | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/sample) | +| Related | [ShortCut Formatter](/ui-kit/react-native/shortcut-formatter-guide) · [Mentions Formatter](/ui-kit/react-native/mentions-formatter-guide) · [All Guides](/ui-kit/react-native/guide-overview) | + + + +`CometChatTextFormatter` is an abstract class for formatting text in the message composer and message bubbles. Extend it to build custom formatters — hashtags, keywords, or any regex-based pattern. + +| Capability | Description | +| --- | --- | +| Text formatting | Auto-format text based on regex patterns and styles | +| Custom styles | Set colors, fonts, and backgrounds for matched text | +| Suggestion list | Display suggestions when tracking character is typed | +| Message handling | Process messages before sending with `handlePreMessageSend` | + +--- + +## Base Class Overview + +The `CometChatTextFormatter` class provides the foundation for all text formatters in React Native: + +```tsx +import { CometChatTextFormatter } from "@cometchat/chat-uikit-react-native"; + +abstract class CometChatTextFormatter { + protected regexPattern: RegExp; + protected trackCharacter: string; + protected loggedInUser?: CometChat.User; + protected messageObject: CometChat.BaseMessage; + protected SuggestionItems: Array; + + // Core methods + setTrackingCharacter(char: string): void; + setRegexPatterns(pattern: RegExp): void; + getFormattedText(inputText: string | null | JSX.Element): string | null | JSX.Element; + handlePreMessageSend(message: CometChat.TextMessage): CometChat.TextMessage; + search(searchKey: string): void; + fetchNext(): void; + setSearchData(data: Array): void; +} +``` + +--- + +## Steps + +### 1. Import the base class + +```tsx +import { CometChatTextFormatter, SuggestionItem } from "@cometchat/chat-uikit-react-native"; +``` + +### 2. Extend it + +```tsx +class HashTagTextFormatter extends CometChatTextFormatter { + constructor() { + super(); + this.setTrackingCharacter("#"); + this.setRegexPatterns(/\B#(\w+)\b/g); + } +} +``` + +### 3. Implement formatting methods + +Override `getFormattedText` to apply custom styling to matched patterns: + +```tsx +import React from "react"; +import { Text } from "react-native"; + +class HashTagTextFormatter extends CometChatTextFormatter { + constructor() { + super(); + this.setTrackingCharacter("#"); + this.setRegexPatterns(/\B#(\w+)\b/g); + } + + getFormattedText(inputText: string | null | JSX.Element): string | null | JSX.Element { + if (!inputText || typeof inputText !== "string") { + return inputText; + } + + const regex = this.getRegexPattern(); + const parts: (string | JSX.Element)[] = []; + let lastIndex = 0; + let match; + + while ((match = regex.exec(inputText)) !== null) { + // Add text before the match + if (match.index > lastIndex) { + parts.push(inputText.slice(lastIndex, match.index)); + } + + // Add styled hashtag + parts.push( + + #{match[1]} + + ); + + lastIndex = match.index + match[0].length; + } + + // Add remaining text + if (lastIndex < inputText.length) { + parts.push(inputText.slice(lastIndex)); + } + + return {parts}; + } +} + +export default HashTagTextFormatter; +``` + +--- + +## Example + +A hashtag formatter used with [CometChatMessageList](/ui-kit/react-native/message-list) and [CometChatMessageComposer](/ui-kit/react-native/message-composer). + + + +```tsx +import React, { JSX } from "react"; +import { Text, TextStyle } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatTextFormatter } from "@cometchat/chat-uikit-react-native"; + +class HashTagTextFormatter extends CometChatTextFormatter { + private hashtagStyle: TextStyle = { + color: "#5dff05", + fontWeight: "bold", + }; + + constructor() { + super(); + this.setTrackingCharacter("#"); + this.setRegexPatterns(/\B#(\w+)\b/g); + } + + setHashtagStyle(style: TextStyle) { + this.hashtagStyle = style; + } + + getFormattedText(inputText: string | null | JSX.Element): string | null | JSX.Element { + if (!inputText || typeof inputText !== "string") { + return inputText; + } + + const regex = this.getRegexPattern(); + const parts: (string | JSX.Element)[] = []; + let lastIndex = 0; + let match; + + // Reset regex lastIndex for global patterns + regex.lastIndex = 0; + + while ((match = regex.exec(inputText)) !== null) { + if (match.index > lastIndex) { + parts.push(inputText.slice(lastIndex, match.index)); + } + + parts.push( + + #{match[1]} + + ); + + lastIndex = match.index + match[0].length; + } + + if (lastIndex < inputText.length) { + parts.push(inputText.slice(lastIndex)); + } + + if (parts.length === 0) { + return inputText; + } + + return {parts}; + } +} + +export default HashTagTextFormatter; +``` + + + +```tsx +import React, { useState, useEffect, useMemo } from "react"; +import { View, SafeAreaView } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; +import HashTagTextFormatter from "./HashTagTextFormatter"; + +function ChatScreen(): React.JSX.Element { + const [chatUser, setChatUser] = useState(); + + useEffect(() => { + CometChat.getUser("uid").then((user) => { + setChatUser(user); + }); + }, []); + + const hashtagFormatter = useMemo(() => new HashTagTextFormatter(), []); + + return ( + + {chatUser && ( + + + + + + )} + + ); +} + +export default ChatScreen; +``` + + + +--- + +## Methods Reference + +| Method | Description | +| --- | --- | +| `setTrackingCharacter(char)` | Character that starts tracking (e.g. `#` for hashtags) | +| `setRegexPatterns(pattern)` | Regex pattern to match text for formatting | +| `getFormattedText(inputText)` | Returns formatted JSX from input text | +| `handlePreMessageSend(message)` | Process message before sending | +| `search(searchKey)` | Search function called when tracking character is typed | +| `fetchNext()` | Fetch next page of suggestions | +| `setSearchData(data)` | Set suggestion list data | +| `setSuggestionItems(items)` | Set the suggestion items array | +| `getSuggestionItems()` | Get current suggestion items | +| `setMessage(message)` | Set the message object in context | +| `getMessage()` | Get the current message object | +| `setUser(user)` | Set the user in context | +| `setGroup(group)` | Set the group in context | +| `setLoggedInUser(user)` | Set the logged-in user | +| `setComposerId(id)` | Set the composer ID for event handling | +| `setId(id)` | Set unique identifier for the formatter | + +--- + +## Advanced: Suggestion List Integration + +For formatters that need to show suggestions (like mentions), implement the `search` method: + +```tsx +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatTextFormatter, SuggestionItem } from "@cometchat/chat-uikit-react-native"; + +class CustomSuggestionFormatter extends CometChatTextFormatter { + constructor() { + super(); + this.setTrackingCharacter(":"); + } + + search(searchKey: string): void { + // Fetch data based on searchKey + const suggestions = this.filterSuggestions(searchKey); + + const suggestionItems = suggestions.map((item) => + new SuggestionItem({ + id: item.id, + name: item.name, + promptText: `:${item.name}:`, + trackingCharacter: ":", + underlyingText: `:${item.code}:`, + }) + ); + + this.setSearchData(suggestionItems); + } + + private filterSuggestions(searchKey: string): any[] { + // Your filtering logic here + return []; + } +} +``` + +--- + +## Next Steps + + + + Add @mentions with styled tokens. + + + Auto-detect and style URLs as clickable links. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react-native/events.mdx b/ui-kit/react-native/events.mdx index 574b57eea..d261a1112 100644 --- a/ui-kit/react-native/events.mdx +++ b/ui-kit/react-native/events.mdx @@ -1,12 +1,27 @@ --- title: "Events" +description: "Listen to UI Kit events for conversations, users, groups, messages, and calls in React Native UI Kit." --- -## Overview + -Events allow for a decoupled, flexible architecture where different parts of the application can interact without having to directly reference each other. This makes it easier to create complex, interactive experiences, as well as to extend and customize the functionality provided by the CometChat UI Kit. +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Import | `import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native";` | +| Conversation events | `ccConversationDeleted`, `ccUpdateConversation` | +| User events | `ccUserBlocked`, `ccUserUnblocked` | +| Group events | `ccGroupCreated`, `ccGroupDeleted`, `ccGroupLeft`, `ccGroupMemberScopeChanged`, `ccGroupMemberKicked`, `ccGroupMemberBanned`, `ccGroupMemberUnbanned`, `ccGroupMemberJoined`, `ccGroupMemberAdded`, `ccOwnershipChanged` | +| Message events | `ccMessageSent`, `ccMessageEdited`, `ccMessageDeleted`, `ccMessageRead`, `ccLiveReaction`, plus SDK listener events | +| Call events | `onIncomingCallAccepted`, `onIncomingCallRejected`, `onCallEnded`, `onCallInitiated`, `onOutgoingCallAccepted`, `onOutgoingCallRejected` | +| UI events | `ccActiveChatChanged` | +| Purpose | Decoupled communication between UI Kit components — subscribe to events to react to changes without direct component references | -Both Components and Composite Components have the ability to emit events. These events are dispatched in response to certain changes or user interactions within the component. By emitting events, these components allow other parts of the application to react to changes or interactions, thus enabling dynamic and interactive behavior within the application. + + +Events provide decoupled communication between UI Kit components. Components emit events in response to user interactions or state changes, allowing other parts of the application to react without direct component references. + +Both Components and Composite Components have the ability to emit events. By emitting events, these components allow other parts of the application to react to changes or interactions, enabling dynamic and interactive behavior within the application. ### CometChatConversationEventListener @@ -93,10 +108,30 @@ It consists of the following events: ### CometChatUIEventListener -UI events, refer to actions or interactions performed by a user within the CometChat's UI Kit. These events are triggered when a user interacts with various UI elements, such as buttons, menus, checkboxes, input fields, or any other interactive components. +UI events refer to actions or interactions performed by a user within the CometChat UI Kit. These events are triggered when a user interacts with various UI elements, such as buttons, menus, checkboxes, input fields, or any other interactive components. It consists of the following events: | Name | Description | | ------------------- | ---------------------------------------------------------------------------- | | ccActiveChatChanged | This event is triggered when the user navigates to a particular chat window. | + + +--- + +## Next Steps + + + + Initialize and authenticate with CometChatUIKit + + + Explore all available UI components + + + Display and manage conversation lists + + + Display messages in a conversation + + diff --git a/ui-kit/react-native/expo-conversation.mdx b/ui-kit/react-native/expo-conversation.mdx new file mode 100644 index 000000000..88acc37f0 --- /dev/null +++ b/ui-kit/react-native/expo-conversation.mdx @@ -0,0 +1,373 @@ +--- +title: "Conversation List + Message View" +sidebarTitle: "Conversation List + Message View" +description: "Build a conversation list + message view layout in Expo with CometChat UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Framework | Expo | +| Components | `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Conversation list → tap → message view | +| Prerequisite | Complete [Expo Integration](/ui-kit/react-native/expo-integration) Steps 1–4 first | +| Pattern | WhatsApp, Telegram, Signal | + + + +This guide builds a standard mobile chat layout — conversation list on one screen, tap to open messages. Users tap a conversation to view and send messages. + +This assumes you've already completed [Expo Integration](/ui-kit/react-native/expo-integration) (project created, UI Kit installed, init + login working). + + + + + +--- + +## What You're Building + +Two screens working together: + +1. **Conversation list** — shows all active conversations (users and groups) +2. **Message view** — displays chat messages for the selected conversation with header, message list, and composer + +--- + +## Step 1 — Create the Messages Component + +Create a `Messages.tsx` file that combines the message header, list, and composer: + + + +```tsx title="Messages.tsx" +import React from "react"; +import { View, StyleSheet } from "react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +interface MessagesProps { + user?: CometChat.User; + group?: CometChat.Group; + onBack: () => void; +} + +const Messages = ({ user, group, onBack }: MessagesProps) => { + return ( + + + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, +}); + +export default Messages; +``` + + +```jsx title="Messages.js" +import React from "react"; +import { View, StyleSheet } from "react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; + +const Messages = ({ user, group, onBack }) => { + return ( + + + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, +}); + +export default Messages; +``` + + + +--- + +## Step 2 — Update App.tsx + +Wire the conversation list and message components together: + + + +```tsx title="App.tsx" +import React, { useEffect, useState } from "react"; +import { ViewStyle } from "react-native"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatConversations, + CometChatUIKit, + CometChatUiKitConstants, + UIKitSettings, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import Messages from "./Messages"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const App = (): React.ReactElement => { + const [loggedIn, setLoggedIn] = useState(false); + const [messageUser, setMessageUser] = useState(); + const [messageGroup, setMessageGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings: UIKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings + .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + const handleConversationPress = (conversation: CometChat.Conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + setMessageUser(conversation.getConversationWith() as CometChat.User); + setMessageGroup(undefined); + } else { + setMessageUser(undefined); + setMessageGroup(conversation.getConversationWith() as CometChat.Group); + } + }; + + const handleBack = () => { + setMessageUser(undefined); + setMessageGroup(undefined); + }; + + return ( + + + + + + {loggedIn && ( + <> + + + {(messageUser || messageGroup) && ( + + )} + + )} + + + + + + ); +}; + +const styles: { fullScreen: ViewStyle } = { + fullScreen: { flex: 1 }, +}; + +export default App; +``` + + +```jsx title="App.js" +import React, { useEffect, useState } from "react"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatConversations, + CometChatUIKit, + CometChatUiKitConstants, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import Messages from "./Messages"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const App = () => { + const [loggedIn, setLoggedIn] = useState(false); + const [messageUser, setMessageUser] = useState(); + const [messageGroup, setMessageGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + const handleConversationPress = (conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + setMessageUser(conversation.getConversationWith()); + setMessageGroup(undefined); + } else { + setMessageUser(undefined); + setMessageGroup(conversation.getConversationWith()); + } + }; + + const handleBack = () => { + setMessageUser(undefined); + setMessageGroup(undefined); + }; + + return ( + + + + + + {loggedIn && ( + <> + + + {(messageUser || messageGroup) && ( + + )} + + )} + + + + + + ); +}; + +export default App; +``` + + + +--- + +## Step 3 — Run the Project + + + +```bash +npx expo run:ios +``` + + +```bash +npx expo run:android +``` + + + +You should see the conversation list. Tap any conversation to open the message view. Use the back button to return to the list. + +--- + +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/react-native/expo-integration-guide.mdx b/ui-kit/react-native/expo-integration-guide.mdx deleted file mode 100644 index 143a01c93..000000000 --- a/ui-kit/react-native/expo-integration-guide.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: "Expo Integration" ---- - -Our React Native UI Kit 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 UI Kit in an expo app you need to use [development builds](https://docs.expo.dev/develop/development-builds/introduction/). You can follow [this](https://docs.expo.dev/guides/local-app-development/) official Expo guide for more details. - -The UI Kit requires a few permissions to run so you need to make some changes in your `app.json` file. - - - -```json -"ios": { - "infoPlist": { - "NSCameraUsageDescription": "This is for Camera permission", - "NSMicrophoneUsageDescription": "This is for Microphone permission" - } -}, -"android": { - "permissions": [ - "android.permission.INTERNET", - "android.permission.CAMERA", - "android.permission.MODIFY_AUDIO_SETTINGS", - "android.permission.RECORD_AUDIO", - "android.permission.ACCESS_NETWORK_STATE" - ] -}, -``` - -For a reference implementation, check out the CometChat React Native [SampleAppExpo](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleAppExpo/) for reference - - - - diff --git a/ui-kit/react-native/expo-integration.mdx b/ui-kit/react-native/expo-integration.mdx new file mode 100644 index 000000000..d6505c8d5 --- /dev/null +++ b/ui-kit/react-native/expo-integration.mdx @@ -0,0 +1,318 @@ +--- +title: "Expo Integration" +sidebarTitle: "Integration" +description: "Add CometChat to an Expo app using development builds in 5 steps: create project, install, init, login, render." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Peer deps | `expo` SDK 50+, `@cometchat/chat-sdk-react-native` | +| Init | `CometChatUIKit.init(UIKitSettings)` — must resolve before `login()` | +| Login | `CometChatUIKit.login({ uid })` — must resolve before rendering components | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Expo Go | Not supported — use development builds | +| Other frameworks | [React Native CLI](/ui-kit/react-native/react-native-cli-integration) | + + + +This guide walks you through adding CometChat to an Expo app using development builds. By the end you'll have a working chat UI. + + +Expo Go is not supported. The CometChat UI Kit requires custom native modules, so you must use [development builds](https://docs.expo.dev/develop/development-builds/introduction/). + + +--- + +## Prerequisites + +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): + +| Credential | Where to find it | +| --- | --- | +| App ID | Dashboard → Your App → Credentials | +| Auth Key | Dashboard → Your App → Credentials | +| Region | Dashboard → Your App → Credentials (e.g. `us`, `eu`, `in`) | + +You also need: +- Node.js (v16+) and npm/yarn installed +- Expo CLI installed (`npm install -g expo-cli`) +- Xcode (for iOS) and Android Studio (for Android) for development builds + + +Auth Key is for development only. In production, generate Auth Tokens server-side via the [REST API](https://api-explorer.cometchat.com/) and use [`loginWithAuthToken()`](/ui-kit/react-native/methods#how-to-login-a-user-with-auth-token). Never ship Auth Keys in client code. + + +--- + +## Step 1 — Create an Expo Project + +```bash +npx create-expo-app ChatApp +cd ChatApp +``` + +--- + +## Step 2 — Install the UI Kit + +```bash +npm install @cometchat/chat-uikit-react-native +``` + +Install the SDK and peer dependencies: + +```bash +npm install @cometchat/chat-sdk-react-native +npm install @react-native-community/datetimepicker +npm install @react-native-clipboard/clipboard +npm install react-native-svg +npm install react-native-video +npm install dayjs +npm install @react-native-async-storage/async-storage +npm install react-native-gesture-handler +npm install react-native-localize +npm install react-native-safe-area-context +``` + +### Configure app.json + +Add required permissions for camera and microphone: + +```json title="app.json" +{ + "expo": { + "ios": { + "infoPlist": { + "NSCameraUsageDescription": "Camera access for video calls", + "NSMicrophoneUsageDescription": "Microphone access for voice/video calls" + } + }, + "android": { + "permissions": [ + "android.permission.INTERNET", + "android.permission.CAMERA", + "android.permission.MODIFY_AUDIO_SETTINGS", + "android.permission.RECORD_AUDIO", + "android.permission.ACCESS_NETWORK_STATE", + "android.permission.WRITE_EXTERNAL_STORAGE", + "android.permission.READ_EXTERNAL_STORAGE", + "android.permission.VIBRATE" + ] + } + } +} +``` + +### Optional: Install Calling SDK + +To enable voice/video calling: + +```bash +npm install @cometchat/calls-sdk-react-native +npm install @react-native-community/netinfo +npm install react-native-background-timer +npm install react-native-callstats +npm install react-native-webrtc +``` + +--- + +## Step 3 — Initialize CometChat + + +`init()` must resolve before you call `login()`. If you call `login()` before init completes, it will fail silently. + + + + +```tsx +import { CometChatUIKit, UIKitSettings } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const COMETCHAT_CONSTANTS = { + APP_ID: "APP_ID", // Replace with your App ID + REGION: "REGION", // Replace with your Region + AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (dev only) +}; + +const uiKitSettings: UIKitSettings = { + appId: COMETCHAT_CONSTANTS.APP_ID, + authKey: COMETCHAT_CONSTANTS.AUTH_KEY, + region: COMETCHAT_CONSTANTS.REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], +}; + +CometChatUIKit.init(uiKitSettings) + .then(() => { + console.log("CometChat UI Kit initialized successfully."); + }) + .catch((error) => { + console.error("CometChat UI Kit initialization failed:", error); + }); +``` + + +```jsx +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const COMETCHAT_CONSTANTS = { + APP_ID: "APP_ID", // Replace with your App ID + REGION: "REGION", // Replace with your Region + AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (dev only) +}; + +const uiKitSettings = { + appId: COMETCHAT_CONSTANTS.APP_ID, + authKey: COMETCHAT_CONSTANTS.AUTH_KEY, + region: COMETCHAT_CONSTANTS.REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, +}; + +CometChatUIKit.init(uiKitSettings) + .then(() => { + console.log("CometChat UI Kit initialized successfully."); + }) + .catch((error) => { + console.error("CometChat UI Kit initialization failed:", error); + }); +``` + + + +--- + +## Step 4 — Login + +After init resolves, log the user in. For development, use one of the pre-created test UIDs: + +`cometchat-uid-1` · `cometchat-uid-2` · `cometchat-uid-3` · `cometchat-uid-4` · `cometchat-uid-5` + + + +```tsx +const UID = "cometchat-uid-1"; // Replace with your actual UID + +CometChatUIKit.login({ uid: UID }) + .then((user: CometChat.User) => { + console.log("Login Successful:", user.getName()); + }) + .catch((error) => { + console.error("Login failed:", error); + }); +``` + + +```jsx +const UID = "cometchat-uid-1"; // Replace with your actual UID + +CometChatUIKit.login({ uid: UID }) + .then((user) => { + console.log("Login Successful:", user.getName()); + }) + .catch((error) => { + console.error("Login failed:", error); + }); +``` + + + + +For production, use [`loginWithAuthToken()`](/ui-kit/react-native/methods#how-to-login-a-user-with-auth-token) instead of Auth Key. Generate tokens server-side via the REST API. + + +--- + +## Step 5 — Choose a Chat Experience + +Integrate a conversation view that suits your app's UX. Each option below includes a step-by-step guide. + +### Conversation List + Message View + +List of conversations on one screen, tap to open messages. Standard mobile chat pattern. + + + + + + + Step-by-step guide to build this layout + + +--- + +### One-to-One / Group Chat + +Single chat window — no conversation list. Good for support chat or focused messaging. + + + + + + + Step-by-step guide to build this layout + + +--- + +### Tab-Based Chat + +Tabbed navigation — Chats, Users, Groups, Calls in separate tabs. Good for full-featured apps. + + + + + + + Step-by-step guide to build this layout + + +--- + +## Running Development Builds + +Since Expo Go is not supported, you need to create development builds: + + + +```bash +npx expo run:ios +``` + + +```bash +npx expo run:android +``` + + + +For more details, see the [Expo local app development guide](https://docs.expo.dev/guides/local-app-development/). + +--- + +## Reference Implementation + +For a complete working example, check out the [SampleAppExpo](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleAppExpo/) repository. + +--- + +## Next Steps + + + + Browse all prebuilt UI components + + + Customize colors, fonts, and styles + + + Chat features included out of the box + + + Explore init, login, logout, and other UI Kit methods + + diff --git a/ui-kit/react-native/expo-one-to-one-chat.mdx b/ui-kit/react-native/expo-one-to-one-chat.mdx new file mode 100644 index 000000000..efb46b22a --- /dev/null +++ b/ui-kit/react-native/expo-one-to-one-chat.mdx @@ -0,0 +1,330 @@ +--- +title: "One-to-One / Group Chat" +sidebarTitle: "One-to-One / Group Chat" +description: "Build a focused one-to-one or group chat experience in Expo with CometChat UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Framework | Expo | +| Components | `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Single chat window — no conversation list | +| Prerequisite | Complete [Expo Integration](/ui-kit/react-native/expo-integration) Steps 1–4 first | +| Pattern | Support chat, embedded widgets, focused messaging | + + + +This guide builds a single chat window — no conversation list. Users go directly into a one-to-one or group chat. Good for support chat, embedded widgets, or any focused messaging experience. + +This assumes you've already completed [Expo Integration](/ui-kit/react-native/expo-integration) (project created, UI Kit installed, init + login working). + + + + + +--- + +## What You're Building + +Three components stacked vertically: + +1. **Chat header** — displays recipient name, avatar, online status, and optional call buttons +2. **Message list** — real-time chat history with scrolling +3. **Message composer** — text input with media, emojis, and send button + +--- + +## Step 1 — Update App.tsx + + + +```tsx title="App.tsx" +import React, { useEffect, useState } from "react"; +import { View, Text, StyleSheet } from "react-native"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatUIKit, + UIKitSettings, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const LOGIN_UID = "cometchat-uid-1"; + +// The user or group to chat with +const CHAT_WITH_UID = "cometchat-uid-2"; // Replace with actual UID +// const CHAT_WITH_GUID = "GUID"; // Uncomment for group chat + +const App = (): React.ReactElement => { + const [loggedIn, setLoggedIn] = useState(false); + const [selectedUser, setSelectedUser] = useState(); + const [selectedGroup, setSelectedGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings: UIKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings + .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: LOGIN_UID }); + setLoggedIn(true); + + // Fetch the user to chat with + const user = await CometChat.getUser(CHAT_WITH_UID); + setSelectedUser(user); + + // For group chat, uncomment below: + // const group = await CometChat.getGroup(CHAT_WITH_GUID); + // setSelectedGroup(group); + } catch (err) { + console.error("Init/login/fetch error:", err); + } + }; + + init(); + }, []); + + return ( + + + + + + {loggedIn && (selectedUser || selectedGroup) ? ( + + + + + + ) : ( + + + Set a user or group UID in App.tsx to start chatting + + + )} + + + + + + ); +}; + +const styles = StyleSheet.create({ + fullScreen: { + flex: 1, + }, + messagesWrapper: { + flex: 1, + }, + emptyState: { + flex: 1, + justifyContent: "center", + alignItems: "center", + backgroundColor: "#F5F5F5", + }, + emptyText: { + color: "#727272", + fontSize: 14, + }, +}); + +export default App; +``` + + +```jsx title="App.js" +import React, { useEffect, useState } from "react"; +import { View, Text, StyleSheet } from "react-native"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatUIKit, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const LOGIN_UID = "cometchat-uid-1"; + +// The user or group to chat with +const CHAT_WITH_UID = "cometchat-uid-2"; // Replace with actual UID +// const CHAT_WITH_GUID = "GUID"; // Uncomment for group chat + +const App = () => { + const [loggedIn, setLoggedIn] = useState(false); + const [selectedUser, setSelectedUser] = useState(); + const [selectedGroup, setSelectedGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: LOGIN_UID }); + setLoggedIn(true); + + // Fetch the user to chat with + const user = await CometChat.getUser(CHAT_WITH_UID); + setSelectedUser(user); + + // For group chat, uncomment below: + // const group = await CometChat.getGroup(CHAT_WITH_GUID); + // setSelectedGroup(group); + } catch (err) { + console.error("Init/login/fetch error:", err); + } + }; + + init(); + }, []); + + return ( + + + + + + {loggedIn && (selectedUser || selectedGroup) ? ( + + + + + + ) : ( + + + Set a user or group UID in App.tsx to start chatting + + + )} + + + + + + ); +}; + +const styles = StyleSheet.create({ + fullScreen: { + flex: 1, + }, + messagesWrapper: { + flex: 1, + }, + emptyState: { + flex: 1, + justifyContent: "center", + alignItems: "center", + backgroundColor: "#F5F5F5", + }, + emptyText: { + color: "#727272", + fontSize: 14, + }, +}); + +export default App; +``` + + + +--- + +## Switching Between User and Group Chat + +To load a group chat instead of one-to-one, replace the `getUser` call with `getGroup`: + +```tsx +const CHAT_WITH_GUID = "GUID"; // Replace with your actual Group ID + +const group = await CometChat.getGroup(CHAT_WITH_GUID); +setSelectedGroup(group); +``` + +--- + +## Step 2 — Run the Project + + + +```bash +npx expo run:ios +``` + + +```bash +npx expo run:android +``` + + + +You should see the chat window load with the conversation for the UID you set. + +--- + +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/react-native/expo-tab-based-chat.mdx b/ui-kit/react-native/expo-tab-based-chat.mdx new file mode 100644 index 000000000..b34e76e73 --- /dev/null +++ b/ui-kit/react-native/expo-tab-based-chat.mdx @@ -0,0 +1,666 @@ +--- +title: "Tab-Based Chat" +sidebarTitle: "Tab-Based Chat" +description: "Build a tab-based messaging UI with Chats, Users, Groups, and Calls in Expo with CometChat UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Framework | Expo | +| Components | `CometChatConversations`, `CometChatUsers`, `CometChatGroups`, `CometChatCallLogs`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Tabbed navigation (Chats, Users, Groups, Calls) + message view | +| Prerequisite | Complete [Expo Integration](/ui-kit/react-native/expo-integration) Steps 1–4 first | +| Pattern | Full-featured messaging app with multiple sections | + + + +This guide builds a tabbed messaging UI — Chats, Users, Groups, and Calls tabs with bottom navigation, plus a message view when an item is selected. Good for full-featured apps that need more than just conversations. + +This assumes you've already completed [Expo Integration](/ui-kit/react-native/expo-integration) (project created, UI Kit installed, init + login working). + + + + + +--- + +## What You're Building + +Three sections working together: + +1. **Tab bar** — switches between Chats, Users, Groups, and Calls +2. **List screens** — renders the list for the active tab +3. **Message view** — header + messages + composer for the selected item + +--- + +## Prerequisites + +Install React Navigation dependencies: + +```bash +npx expo install @react-navigation/native @react-navigation/bottom-tabs @react-navigation/native-stack react-native-screens +``` + +--- + +## Step 1 — Create the Tab Screens + +Create individual screen components for each tab: + + + +```tsx title="screens/ConversationsScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { + CometChatConversations, + CometChatUiKitConstants, +} from "@cometchat/chat-uikit-react-native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type Props = { + navigation: NativeStackNavigationProp; +}; + +export function ConversationsScreen({ navigation }: Props) { + const handleItemPress = (conversation: CometChat.Conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + const user = conversation.getConversationWith() as CometChat.User; + navigation.navigate("Messages", { user }); + } else { + const group = conversation.getConversationWith() as CometChat.Group; + navigation.navigate("Messages", { group }); + } + }; + + return ( + + + + ); +} +``` + +```tsx title="screens/UsersScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type Props = { + navigation: NativeStackNavigationProp; +}; + +export function UsersScreen({ navigation }: Props) { + const handleItemPress = (user: CometChat.User) => { + navigation.navigate("Messages", { user }); + }; + + return ( + + + + ); +} +``` + +```tsx title="screens/GroupsScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type Props = { + navigation: NativeStackNavigationProp; +}; + +export function GroupsScreen({ navigation }: Props) { + const handleItemPress = (group: CometChat.Group) => { + navigation.navigate("Messages", { group }); + }; + + return ( + + + + ); +} +``` + +```tsx title="screens/CallLogsScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; + +export function CallLogsScreen() { + return ( + + + + ); +} +``` + + +```jsx title="screens/ConversationsScreen.js" +import React from "react"; +import { View } from "react-native"; +import { + CometChatConversations, + CometChatUiKitConstants, +} from "@cometchat/chat-uikit-react-native"; + +export function ConversationsScreen({ navigation }) { + const handleItemPress = (conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + const user = conversation.getConversationWith(); + navigation.navigate("Messages", { user }); + } else { + const group = conversation.getConversationWith(); + navigation.navigate("Messages", { group }); + } + }; + + return ( + + + + ); +} +``` + +```jsx title="screens/UsersScreen.js" +import React from "react"; +import { View } from "react-native"; +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; + +export function UsersScreen({ navigation }) { + const handleItemPress = (user) => { + navigation.navigate("Messages", { user }); + }; + + return ( + + + + ); +} +``` + +```jsx title="screens/GroupsScreen.js" +import React from "react"; +import { View } from "react-native"; +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; + +export function GroupsScreen({ navigation }) { + const handleItemPress = (group) => { + navigation.navigate("Messages", { group }); + }; + + return ( + + + + ); +} +``` + +```jsx title="screens/CallLogsScreen.js" +import React from "react"; +import { View } from "react-native"; +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; + +export function CallLogsScreen() { + return ( + + + + ); +} +``` + + + +--- + +## Step 2 — Create the Messages Screen + + + +```tsx title="screens/MessagesScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; +import { RouteProp } from "@react-navigation/native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type MessagesRouteParams = { + Messages: { + user?: CometChat.User; + group?: CometChat.Group; + }; +}; + +type Props = { + route: RouteProp; + navigation: NativeStackNavigationProp; +}; + +export function MessagesScreen({ route, navigation }: Props) { + const { user, group } = route.params; + + return ( + + navigation.goBack()} + showBackButton + /> + + + + ); +} +``` + + +```jsx title="screens/MessagesScreen.js" +import React from "react"; +import { View } from "react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; + +export function MessagesScreen({ route, navigation }) { + const { user, group } = route.params; + + return ( + + navigation.goBack()} + showBackButton + /> + + + + ); +} +``` + + + +--- + +## Step 3 — Set Up Navigation + + + +```tsx title="App.tsx" +import React, { useEffect, useState } from "react"; +import { Image, StyleSheet } from "react-native"; +import { NavigationContainer } from "@react-navigation/native"; +import { createNativeStackNavigator } from "@react-navigation/native-stack"; +import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatUIKit, + UIKitSettings, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +import { ConversationsScreen } from "./screens/ConversationsScreen"; +import { UsersScreen } from "./screens/UsersScreen"; +import { GroupsScreen } from "./screens/GroupsScreen"; +import { CallLogsScreen } from "./screens/CallLogsScreen"; +import { MessagesScreen } from "./screens/MessagesScreen"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const Tab = createBottomTabNavigator(); +const Stack = createNativeStackNavigator(); + +function TabNavigator() { + return ( + + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + + ); +} + +export default function App() { + const [loggedIn, setLoggedIn] = useState(false); + + useEffect(() => { + const init = async () => { + const uiKitSettings: UIKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings + .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + if (!loggedIn) return null; + + return ( + + + + + + + + + + + + + + + ); +} + +const styles = StyleSheet.create({ + tabBar: { + backgroundColor: "#FFFFFF", + borderTopWidth: 1, + borderTopColor: "#E8E8E8", + paddingBottom: 5, + paddingTop: 5, + height: 60, + }, + tabIcon: { + width: 24, + height: 24, + }, +}); +``` + + +```jsx title="App.js" +import React, { useEffect, useState } from "react"; +import { Image, StyleSheet } from "react-native"; +import { NavigationContainer } from "@react-navigation/native"; +import { createNativeStackNavigator } from "@react-navigation/native-stack"; +import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatUIKit, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +import { ConversationsScreen } from "./screens/ConversationsScreen"; +import { UsersScreen } from "./screens/UsersScreen"; +import { GroupsScreen } from "./screens/GroupsScreen"; +import { CallLogsScreen } from "./screens/CallLogsScreen"; +import { MessagesScreen } from "./screens/MessagesScreen"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const Tab = createBottomTabNavigator(); +const Stack = createNativeStackNavigator(); + +function TabNavigator() { + return ( + + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + + ); +} + +export default function App() { + const [loggedIn, setLoggedIn] = useState(false); + + useEffect(() => { + const init = async () => { + const uiKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + if (!loggedIn) return null; + + return ( + + + + + + + + + + + + + + + ); +} + +const styles = StyleSheet.create({ + tabBar: { + backgroundColor: "#FFFFFF", + borderTopWidth: 1, + borderTopColor: "#E8E8E8", + paddingBottom: 5, + paddingTop: 5, + height: 60, + }, + tabIcon: { + width: 24, + height: 24, + }, +}); +``` + + + + +Download tab icons from the [CometChat UI Kit assets folder on GitHub](https://github.com/cometchat/cometchat-uikit-react-native) and place them in your `assets/` folder. + + +--- + +## Step 4 — Run the Project + + + +```bash +npx expo run:ios +``` + + +```bash +npx expo run:android +``` + + + +You should see the tab bar at the bottom. Switch between Chats, Users, Groups, and Calls — tapping any item navigates to the message view. + +--- + +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/react-native/extensions.mdx b/ui-kit/react-native/extensions.mdx index d9606f34e..b2a255887 100644 --- a/ui-kit/react-native/extensions.mdx +++ b/ui-kit/react-native/extensions.mdx @@ -1,16 +1,27 @@ --- title: "Extensions" +description: "Enable built-in extensions like stickers, polls, collaborative documents, message translation, and link previews in CometChat's React Native UI Kit." --- + +**Quick Reference for AI Agents & Developers** + +Key components used by extensions: +- **Message Composer** → [CometChatMessageComposer](/ui-kit/react-native/message-composer) (stickers, polls, whiteboard, document) +- **Message List** → [CometChatMessageList](/ui-kit/react-native/message-list) (translation, link preview, thumbnails) + +Extensions are enabled from the [CometChat Dashboard](https://app.cometchat.com) — no additional code required. + + ## Overview -CometChat’s UI Kit comes with built-in support for a wide variety of extensions that provide additional functionality. These extensions enhance the chatting experience, making it more interactive, secure, and efficient. +CometChat's UI Kit comes with built-in support for a wide variety of extensions that provide additional functionality. These extensions enhance the chatting experience, making it more interactive, secure, and efficient. -Activating any of the extensions in CometChat is a simple process done through your application's dashboard. Refer to our guide For detailed information on [Extensions](/fundamentals/extensions-overview) +Activating any extension in CometChat is a simple process done through your application's dashboard. For detailed information, refer to the [Extensions](/fundamentals/extensions-overview) guide. -Once you have successfully enabled the desired extension in your dashboard, it will be reflected in your CometChat application upon initialization and successful login. Please note, that the extension features will only be available if they are supported by CometChat UI Kit. +Once you have successfully enabled the desired extension in your dashboard, it will be reflected in your CometChat application upon initialization and successful login. The extension features will only be available if they are supported by the CometChat UI Kit. -CometChat’s UI Kit offers built-in support for 12 powerful extensions. This seamless integration makes it easy for you to enhance your chat application with engaging features without any extra coding effort. Just enable the desired extensions from the CometChat Dashboard, and they will be automatically reflected in the relevant components of your application, providing a richer and more engaging experience for your users. +CometChat's UI Kit offers built-in support for 12 powerful extensions. This seamless integration makes it easy to enhance your chat application with engaging features without any extra coding effort. Just enable the desired extensions from the CometChat Dashboard, and they will be automatically reflected in the relevant components of your application, providing a richer and more engaging experience for your users. ## Built-in Extensions @@ -18,9 +29,9 @@ Here's a guide on how you can enable and integrate these extensions: ### Stickers -The Stickers extension allows users to express their emotions more creatively. It adds a much-needed fun element to the chat by allowing users to send various pre-designed stickers. For a comprehensive understanding and guide on implementing and using the Sticker Extension, refer to our specific guide on the [Sticker Extension](/fundamentals/stickers). +The Stickers extension allows users to express their emotions more creatively. It adds a fun element to the chat by allowing users to send various pre-designed stickers. For a comprehensive guide on implementing the Sticker Extension, refer to the [Sticker Extension](/fundamentals/stickers) documentation. -Once you have successfully activated the [Sticker Extension](/fundamentals/stickers) from your CometChat Dashboard, the feature will automatically be incorporated into the [Message Composer](/ui-kit/react-native/message-composer) component of UI Kits. +Once you have activated the [Sticker Extension](/fundamentals/stickers) from your CometChat Dashboard, the feature will automatically be incorporated into the [Message Composer](/ui-kit/react-native/message-composer) component. @@ -28,9 +39,9 @@ Once you have successfully activated the [Sticker Extension](/fundamentals/stick ### Polls -The Polls extension enhances group discussions by allowing users to create polls. Users can ask questions with a predefined list of answers, enabling a quick, organized way to gather group opinions. For a comprehensive understanding and guide on implementing and using the Polls Extension, refer to our specific guide on the [Polls Extension](/fundamentals/polls). +The Polls extension enhances group discussions by allowing users to create polls. Users can ask questions with a predefined list of answers, enabling a quick, organized way to gather group opinions. For a comprehensive guide, refer to the [Polls Extension](/fundamentals/polls) documentation. -Once you have successfully activated the [Polls Extension](/fundamentals/polls) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react-native/message-composer) component of UI Kits. +Once you have activated the [Polls Extension](/fundamentals/polls) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react-native/message-composer) component. @@ -38,9 +49,9 @@ Once you have successfully activated the [Polls Extension](/fundamentals/polls) ### Collaborative Whiteboard -The Collaborative Whiteboard extension facilitates real-time collaboration. Users can draw, brainstorm, and share ideas on a shared digital whiteboard. For a comprehensive understanding and guide on implementing and using the Collaborative Whiteboard Extension, refer to our specific guide on the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard). +The Collaborative Whiteboard extension facilitates real-time collaboration. Users can draw, brainstorm, and share ideas on a shared digital whiteboard. For a comprehensive guide, refer to the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard) documentation. -Once you have successfully activated the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react-native/message-composer) component of UI Kits. +Once you have activated the [Collaborative Whiteboard Extension](/fundamentals/collaborative-whiteboard) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react-native/message-composer) component. @@ -48,9 +59,9 @@ Once you have successfully activated the [Collaborative Whiteboard Extension](/f ### Collaborative Document -With the Collaborative Document extension, users can work together on a shared document. This feature is essential for remote teams where document collaboration is a recurring requirement. For a comprehensive understanding and guide on implementing and using the Collaborative Document Extension, refer to our specific guide on the [Collaborative Document Extension](/fundamentals/collaborative-document). +With the Collaborative Document extension, users can work together on a shared document. This feature is essential for remote teams where document collaboration is a recurring requirement. For a comprehensive guide, refer to the [Collaborative Document Extension](/fundamentals/collaborative-document) documentation. -Once you have successfully activated the [Collaborative Document Extension](/fundamentals/collaborative-document) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react-native/message-composer) component of UI Kits. +Once you have activated the [Collaborative Document Extension](/fundamentals/collaborative-document) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [Message Composer](/ui-kit/react-native/message-composer) component. @@ -58,9 +69,9 @@ Once you have successfully activated the [Collaborative Document Extension](/fun ### Message Translation -The Message Translation extension in CometChat is designed to translate any message into your local locale. It eliminates language barriers, making the chat more inclusive. For a comprehensive understanding and guide on implementing and using the Message Translation Extension, refer to our specific guide on the [Message Translation Extension](/fundamentals/message-translation). +The Message Translation extension translates any message into your local locale. It eliminates language barriers, making the chat more inclusive. For a comprehensive guide, refer to the [Message Translation Extension](/fundamentals/message-translation) documentation. -Once you have successfully activated the [Message Translation Extension](/fundamentals/message-translation) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of [MessageList Component](/ui-kit/react-native/message-list) component of UI Kits. +Once you have activated the [Message Translation Extension](/fundamentals/message-translation) from your CometChat Dashboard, the feature will automatically be incorporated into the Action Sheet of the [MessageList](/ui-kit/react-native/message-list) component. @@ -68,9 +79,9 @@ Once you have successfully activated the [Message Translation Extension](/fundam ### Link Preview -The Link Preview extension provides a summary of the URL shared in the chat. It includes the title, a description, and a thumbnail image from the web page. For a comprehensive understanding and guide on implementing and using the Link Preview Extension, refer to our specific guide on the [Link Preview Extension](/fundamentals/link-preview). +The Link Preview extension provides a summary of any URL shared in the chat. It includes the title, a description, and a thumbnail image from the web page. For a comprehensive guide, refer to the [Link Preview Extension](/fundamentals/link-preview) documentation. -Once you have successfully activated the [Link Preview Extension](/fundamentals/link-preview) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/react-native/message-list) component of UI Kits. +Once you have activated the [Link Preview Extension](/fundamentals/link-preview) from your CometChat Dashboard, the feature will automatically be incorporated into the message bubble of the [MessageList](/ui-kit/react-native/message-list) component. @@ -78,10 +89,29 @@ Once you have successfully activated the [Link Preview Extension](/fundamentals/ ### Thumbnail Generation -The Thumbnail Generation extension automatically creates a smaller preview image whenever a larger image is shared, helping to reduce the upload/download time and bandwidth usage. For a comprehensive understanding and guide on implementing and using the Thumbnail Generation Extension, refer to our specific guide on the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation). +The Thumbnail Generation extension automatically creates a smaller preview image whenever a larger image is shared, helping reduce upload/download time and bandwidth usage. For a comprehensive guide, refer to the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation) documentation. -Once you have successfully activated the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation) from your CometChat Dashboard, the feature will automatically be incorporated into the Message Bubble of [MessageList Component](/ui-kit/react-native/message-list) component of UI Kits. +Once you have activated the [Thumbnail Generation Extension](/fundamentals/thumbnail-generation) from your CometChat Dashboard, the feature will automatically be incorporated into the message bubble of the [MessageList](/ui-kit/react-native/message-list) component. + +--- + +## Next Steps + + + + Explore messaging, receipts, typing indicators, and more + + + Add voice and video calling to your app + + + Customize the message input component + + + Customize how messages are displayed + + diff --git a/ui-kit/react-native/getting-started.mdx b/ui-kit/react-native/getting-started.mdx deleted file mode 100644 index ca4836dfd..000000000 --- a/ui-kit/react-native/getting-started.mdx +++ /dev/null @@ -1,515 +0,0 @@ ---- -title: "Getting Started" ---- - -## Start your first conversation - -CometChat UI Kit for React Native is a collection of prebuilt UI components designed to simplify the development of an in-app chat with all the essential messaging features. Our UI Kit offers light and dark themes, various fonts, colors, and additional customization options. - -CometChat UI Kit supports both one-to-one and group conversations. Follow the guide below to initiate conversations from scratch using CometChat React Native UI Kit. - - - - - -## Prerequisites - -Before installing **UI Kit for React Native**, you need to create a CometChat application on the CometChat Dashboard, which comprises everything required in a chat service including users, groups, calls & messages. You will need the `App ID` , `AuthKey`, `Region` of your CometChat application when initialising the SDK. - -**i. Register on CometChat** - -* To install **UI Kit for React Native**, you need to first register on **CometChat Dashboard**. [Click here to sign up](https://app.cometchat.com/login). - -**ii. Get Your Application Keys** - -* Create a **new app** -* Head over to the **QuickStart** or **API & Auth Keys section** and note the **App ID**, **Auth Key**, and **Region**. - - - -Each CometChat application can be integrated with a single client app. Within the same application, users can communicate with each other across all platforms, whether they are on mobile devices or on the web. - - - -*** - -## Getting Started - -You can quickly start building a modern messaging experience into your app by installing the new UI Kit, an add-on for the CometChat React Native SDK. - -*** - -Step 1 - -### Create a project - -To get started, open `terminal` and create a new project using below command. - - - -```sh -npx @react-native-community/cli init ChatApp -``` - - - -The CometChat React Native UI Kit is officially built and tested with React Native version 0.77.0 and above, up to the latest stable release. While it may work with older versions, they are not officially supported and could lead to unexpected issues. - - - - - - - -*** - -Step 2 - -### Add Dependency - -You can install **UI Kit for React Native** through using below command. - - - -```sh -npm i @cometchat/chat-uikit-react-native -``` - - - - - -*** - -#### Other Dependencies - - - -```sh -npm i @cometchat/chat-sdk-react-native -npm i @react-native-community/datetimepicker -npm i @react-native-clipboard/clipboard -npm i react-native-svg -npm i react-native-video -npm i dayjs -npm i @react-native-async-storage/async-storage -npm i react-native-gesture-handler -npm i react-native-localize - -``` - - - - - -*** - -#### Add Permissions for android - -Open `AndroidManifest.xml` file from `android/app/src/main` location and add below permissions - - - -```xml - - - - - - -``` - - - - - - - -Please make sure Android SDK path is set in the `ANDROID_HOME` environment variable or in `local.properties` via the field `sdk.dir`. - - - -#### Install @cometchat/calls-sdk-react-native Package (Optional) - -To enable calling functionality in your application, you need to install the Calling SDK separately within your project. - - - -React Native UI Kit supports Calls SDK V3 or higher. - - - -1. You can install `@cometchat/calls-sdk-react-native` Calling SDK for React Native using below command. - - - - ```sh - npm i @cometchat/calls-sdk-react-native - ``` - - - - - -2. Install dependancies required for call SDK to work - - - - ```sh - npm i @cometchat/chat-sdk-react-native - npm i @react-native-async-storage/async-storage - npm i @react-native-community/netinfo - npm i react-native-background-timer - npm i react-native-callstats - npm i react-native-webrtc - ``` - - - - - -3. Add permissions - - **Android:** - - - - ```xml - - - - - - ``` - - - - - - **iOS:** - - - - ```xml - NSCameraUsageDescription - This is for Camera permission - NSMicrophoneUsageDescription - This is for Mic permission - ``` - - - - - -*** - -Step 3 - -## Initialise CometChatUIKit - -To integrate and run CometChat UI Kit in your app, you need to initialize it beforehand. - -The Init method initializes the settings required for CometChat. Please ensure to call this method before invoking any other methods from CometChat UI Kit or CometChat SDK. - - - -The Auth Key is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](/ui-kit/react-native/methods#how-to-login-a-user-with-auth-token) method to log in securely. - - - - - -```ts -import React, { useEffect } from "react"; -import { - CometChatUIKit, - UIKitSettings, -} from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; - -useEffect(() => { - let uikitSettings: UIKitSettings = { - appId: "Enter your App ID here", // Replace with your CometChat App ID - authKey: "Enter your Auth Key here", // Replace with your App Auth Key - region: "Enter your App Region here", // e.g., "us", "in" - subscriptionType: CometChat.AppSettings - .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], - }; - - CometChatUIKit.init(uikitSettings) - .then(() => { - console.log("CometChatUiKit successfully initialized"); - }) - .catch((error) => { - console.log("Initialization failed with exception:", error); - }); -}, []); -``` - - - - - -Step 4 - -## Login User - -For login, you require a UID. You can create your own users on the CometChat Dashboard or via API. We have pre-generated test users: cometchat-uid-1, cometchat-uid-2, cometchat-uid-3, cometchat-uid-4, cometchat-uid-5. - -The Login method returns the User object containing all the information of the logged-in user. - - - -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](/ui-kit/react-native/methods#how-to-login-a-user-with-auth-token) instead of an Auth Key to ensure enhanced security. - - - - - -```ts -// Replace with the actual user ID you want to log in -const uid = ""; - -// Login user with CometChatUIKit -CometChatUIKit.login({ uid }) - .then((user) => { - // Login successful - console.log(`User logged in successfully: ${user.getName()}`); - }) - .catch((error) => { - // Handle login error - console.error("Login failed with error:", error); - }); -``` - - - - - -*** - -Step 5 - -### Render Conversations with Messages - -#### Loading the Conversations Component - - - - - - - -```tsx -import React, { useEffect, useState } from "react"; -import { SafeAreaView, ViewStyle } from "react-native"; -import { - CometChatConversations, - CometChatUIKit, - CometChatUiKitConstants, - UIKitSettings, - CometChatThemeProvider, - CometChatI18nProvider, -} from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; - -import Messages from "./Messages"; - -import { GestureHandlerRootView } from "react-native-gesture-handler"; - -/* -------------------------------------------------------------------------- */ -/* ⚙️ Replace the placeholders below with your own CometChat credentials. */ -/* -------------------------------------------------------------------------- */ -const APP_ID = ""; // e.g. "123456abc" -const AUTH_KEY = ""; // e.g. "0b1c2d3e4f5g6h7i8j9k" -const REGION = ""; // e.g. "us" | "eu" | "in" -const DEMO_UID = ""; // e.g. "john_doe" -/* -------------------------------------------------------------------------- */ - -/** - * App - * --- - * The root component: - * 1. Initializes the CometChat UI Kit. - * 2. Logs a demo user in. - * 3. Shows either the conversation list or an active chat screen. - */ -const App = (): React.ReactElement => { - /* ------------------------------------------------------------------ */ - /* Local state */ - /* ------------------------------------------------------------------ */ - const [loggedIn, setLoggedIn] = useState(false); - const [messageUser, setMessageUser] = useState(); - const [messageGroup, setMessageGroup] = useState(); - - /* ------------------------------------------------------------------ */ - /* One-time initialization */ - /* ------------------------------------------------------------------ */ - useEffect(() => { - const init = async () => { - // 1️⃣ Configure the UI Kit. - const uiKitSettings: UIKitSettings = { - appId: APP_ID, - authKey: AUTH_KEY, - region: REGION, - subscriptionType: CometChat.AppSettings - .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], - }; - - try { - await CometChatUIKit.init(uiKitSettings); - console.log("[CometChatUIKit] initialized"); - - // 2️⃣ Login. - await CometChatUIKit.login({ uid: DEMO_UID }); - setLoggedIn(true); - } catch (err) { - console.error("[CometChatUIKit] init/login error", err); - } - }; - - init(); - }, []); - - /* ------------------------------------------------------------------ */ - /* Render */ - /* ------------------------------------------------------------------ */ - return ( - - - - - {/* Show conversations only after the user is logged in */} - {loggedIn && ( - <> - {/* Conversation list (hidden when a chat is open) */} - { - if ( - conversation.getConversationType() === - CometChatUiKitConstants.ConversationTypeConstants.user - ) { - setMessageUser( - conversation.getConversationWith() as CometChat.User, - ); - return; - } - setMessageGroup( - conversation.getConversationWith() as CometChat.Group, - ); - }} - /> - - {/* Active chat screen */} - {(messageUser || messageGroup) && ( - { - setMessageUser(undefined); - setMessageGroup(undefined); - }} - /> - )} - - )} - - - - - ); -}; - -/* -------------------------------------------------------------------------- */ -/* Styles */ -/* -------------------------------------------------------------------------- */ -const styles: { fullScreen: ViewStyle } = { - fullScreen: { flex: 1 }, -}; - -export default App; -``` - - - - - -#### Loading the Messages Component - - - - - -* The Messages component allows users to view and send messages in both one-on-one and group conversations. - - - -```tsx -import React from "react"; -import { View, StyleSheet } from "react-native"; -import { - CometChatMessageHeader, - CometChatMessageList, - CometChatMessageComposer, -} from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; - -/** - * Messages - * -------- - * A self-contained chat screen that combines the **CometChatMessageHeader**, **CometChatMessageList**, - * and **CometChatMessageComposer** provided by the CometChat React-Native UI Kit. - * - * Props - * ----- - * • `user` – (CometChat.User, optional) Target user for a 1-to-1 conversation. - * • `group` – (CometChat.Group, optional) Target group for a group conversation. - * • `onBack`— () ⇒ void Callback fired when the back button in the header is pressed. - * - */ -const Messages = ({ - user, - group, - onBack, -}: { - user?: CometChat.User; - group?: CometChat.Group; - onBack: () => void; -}) => { - return ( - - {/* Top bar: avatar, name & back button */} - - - {/* Scrollable list of chat messages */} - - - {/* Input field + action buttons (emoji, attach, send, etc.) */} - - - ); -}; - -const styles = StyleSheet.create({ - /** Ensures the component stretches to use all available space */ - root: { - flex: 1, - }, -}); - -export default Messages; -``` - - - - diff --git a/ui-kit/react-native/group-members.mdx b/ui-kit/react-native/group-members.mdx index bb698e4d8..ebed45a79 100644 --- a/ui-kit/react-native/group-members.mdx +++ b/ui-kit/react-native/group-members.mdx @@ -1,778 +1,768 @@ --- title: "Group Members" +description: "Display and manage group members with CometChatGroupMembers component in React Native UI Kit, including member roles, permissions, and moderation actions." --- -## Overview + +```json +{ + "component": "CometChatGroupMembers", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatGroupMembers } from \"@cometchat/chat-uikit-react-native\";", + "description": "Scrollable, searchable list of members in a specific group with roles, scopes, online status, and member management actions.", + "primaryOutput": { + "prop": "onItemPress", + "type": "(groupMember: CometChat.GroupMember) => void" + }, + "props": { + "data": { + "group": { + "type": "CometChat.Group", + "required": true, + "note": "The group whose members are displayed" + }, + "groupMemberRequestBuilder": { + "type": "CometChat.GroupMembersRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "searchRequestBuilder": { + "type": "CometChat.GroupMembersRequestBuilder", + "default": "undefined" + }, + "searchKeyword": { + "type": "string", + "default": "\"\"" + } + }, + "callbacks": { + "onItemPress": "(groupMember: CometChat.GroupMember) => void", + "onItemLongPress": "(groupMember: CometChat.GroupMember) => void", + "onBack": "() => void", + "onSelection": "(list: CometChat.GroupMember[]) => void", + "onSubmit": "(list: Array) => void", + "onError": "() => void", + "onEmpty": "() => void", + "onLoad": "(list: CometChat.GroupMember[]) => void" + }, + "visibility": { + "hideHeader": { "type": "boolean", "default": false }, + "showBackButton": { "type": "boolean", "default": false }, + "hideSearch": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "hideLoadingState": { "type": "boolean", "default": false }, + "usersStatusVisibility": { "type": "boolean", "default": true }, + "hideKickMemberOption": { "type": "boolean", "default": false }, + "hideBanMemberOption": { "type": "boolean", "default": false }, + "hideScopeChangeOption": { "type": "boolean", "default": false }, + "excludeOwner": { "type": "boolean", "default": false }, + "hideSubmitButton": { "type": "boolean", "default": false } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["single", "multiple", "none"], + "default": "none" + } + }, + "viewSlots": { + "ItemView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "LeadingView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "TitleView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "SubtitleView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "TrailingView": "(groupMember: CometChat.GroupMember) => JSX.Element", + "LoadingView": "() => JSX.Element", + "EmptyView": "() => JSX.Element", + "ErrorView": "() => JSX.Element", + "AppBarOptions": "() => JSX.Element" + } + }, + "events": [ + { + "name": "ccGroupMemberKicked", + "payload": "IGroupMemberKickedBanned", + "description": "Triggered when a group member is kicked" + }, + { + "name": "ccGroupMemberBanned", + "payload": "IGroupMemberKickedBanned", + "description": "Triggered when a group member is banned" + }, + { + "name": "ccGroupMemberScopeChanged", + "payload": "IGroupMemberScopeChanged", + "description": "Triggered when a group member's scope is changed" + } + ], + "sdkListeners": [ + "onGroupMemberScopeChanged", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onMemberAddedToGroup", + "onGroupMemberLeft", + "onGroupMemberJoined" + ], + "compositionExample": { + "description": "Group members panel wired to group chat view", + "components": [ + "CometChatGroupMembers", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "Fetch group -> pass to GroupMembers, MessageHeader, MessageList, MessageComposer" + }, + "types": { + "SelectionMode": { + "single": "Select one member at a time", + "multiple": "Select multiple members", + "none": "No selection mode" + } + } +} +``` + + +## Where It Fits -`CometChatGroupMembers` is a versatile [Component](/ui-kit/react-native/components-overview#components) designed to showcase all users who are either added to or invited to a group, thereby enabling them to participate in group discussions, access shared content, and engage in collaborative activities. Group members have the capability to communicate in real-time through messaging, voice and video calls, and various other interactions. Additionally, they can interact with each other, share files, and join calls based on the permissions established by the group administrator or owner. +`CometChatGroupMembers` is a panel component that renders the member list for a specific group. It requires a `group` prop and provides built-in member management actions (kick, ban, scope change) based on the logged-in user's role. Typically rendered alongside the message view in a group chat layout. -*** - -## Usage - -### Integration - -`CometChatGroupMembers`, as a Composite Component, offers flexible integration options, allowing it to be launched directly via button clicks or any user-triggered action. Additionally, it seamlessly integrates into tab view controllers. With group members, users gain access to a wide range of parameters and methods for effortless customization of its user interface. - -The following code snippet exemplifies how you can seamlessly integrate the GroupMembers component into your application. +--- -If you're defining the Group members within the XML code, you'll need to extract them and set them on the Group object using the appropriate method. +## Minimal Render - - -```tsx +```tsx lines +import { useEffect, useState } from "react"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { CometChatGroupsMembers } from "@cometchat/chat-uikit-react-native"; +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -function App(): React.JSX.Element { +function GroupMembersDemo() { const [group, setGroup] = useState(undefined); - const getGroup = async () => { - const group = await CometChat.getGroup("guid"); - setGroup(group); - }; - useEffect(() => { - //login - getGroup(); - }); + CometChat.getGroup("GROUP_GUID").then(setGroup); + }, []); - return ( - <> - {group && } - - ); + return group ? : null; } + +export default GroupMembersDemo; ``` - +--- - +## Filtering Group Members -*** +Pass a `CometChat.GroupMembersRequestBuilder` to `groupMemberRequestBuilder`. Pass the builder instance — not the result of `.build()`. -### Actions +The [GroupMembersRequestBuilder](/sdk/react-native/retrieve-group-members) enables you to filter and customize the group members list based on available parameters. The following are the parameters available in [GroupMembersRequestBuilder](/sdk/react-native/retrieve-group-members): -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +| Methods | Type | Description | +| -------------------- | -------------- | ------------------------------------------------------------------------------------------------- | +| **setLimit** | number | sets the number of group members that can be fetched in a single request, suitable for pagination | +| **setSearchKeyword** | string | used for fetching group members matching the passed string | +| **setScopes** | Array\ | used for fetching group members based on multiple scopes | -##### onItemPress +```tsx lines +import { useEffect, useState } from "react"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -Function invoked when a user item is clicked, typically used to open a user profile or chat screen. +function FilteredGroupMembers() { + const [group, setGroup] = useState(undefined); - - -```tsx -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; + useEffect(() => { + CometChat.getGroup("GROUP_GUID").then(setGroup); + }, []); -const onPressHandler = (groupMember: CometChat.GroupMember) => { - //code -}; + if (!group) return null; -return ; + return ( + + ); +} ``` - +### Filter Recipes - +| Recipe | Code | +| --- | --- | +| Limit to 10 per page | `new CometChat.GroupMembersRequestBuilder("GUID").setLimit(10)` | +| Search by keyword | `new CometChat.GroupMembersRequestBuilder("GUID").setSearchKeyword("john")` | +| Admins and moderators only | `new CometChat.GroupMembersRequestBuilder("GUID").setScopes(["admin", "moderator"])` | -*** +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. -##### onnItemLongPress +### SearchRequestBuilder -Function executed when a user item is long-pressed, allowing additional actions like delete or block. +The `searchRequestBuilder` prop accepts a separate `GroupMembersRequestBuilder` for filtering when the search bar is active. This allows you to keep uniformity between the displayed Group Members List and searched Group Members List. - - -```tsx -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; +```tsx lines +import { useEffect, useState } from "react"; import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -const onLongPressHandler = (groupMember: CometChat.GroupMember) => { - //code -}; - -return ; -``` - - - - +function SearchGroupMembers() { + const [group, setGroup] = useState(undefined); -*** + useEffect(() => { + CometChat.getGroup("GROUP_GUID").then(setGroup); + }, []); -##### onBack + if (!group) return null; -`OnBackPressListener` is triggered when you press the back button in the app bar. It has a predefined behavior; when clicked, it navigates to the previous activity. However, you can override this action using the following code snippet. + const searchRequestBuilder = new CometChat.GroupMembersRequestBuilder( + group.getGuid() + ) + .setScopes(["admin"]) + .setSearchKeyword("custom-keyword"); - - -```tsx -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; + return ( + + ); +} +``` -const onBackHandler = () => { - //code -}; +Refer to [GroupMembersRequestBuilder](/sdk/react-native/retrieve-group-members) for the full builder API. -return ; -``` +--- - +## Actions and Events - +### Callback Props -*** +#### onItemPress -##### onSelection +Fires when a member row is tapped. -Called when a item from the fetched list is selected, useful for multi-selection features. +```tsx lines +onItemPress?: (groupMember: CometChat.GroupMember) => void +``` - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onSelectionHandler = (selection: Array) => { - //code -}; - -return ( - -); +function GroupMembersWithPress({ group }: { group: CometChat.Group }) { + return ( + { + console.log("Selected member:", member.getName()); + }} + /> + ); +} ``` - - - +#### onItemLongPress -*** +Fires when a member item is long-pressed, allowing additional actions like delete or block. -##### onError - -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Users component. +```tsx lines +onItemLongPress?: (groupMember: CometChat.GroupMember) => void +``` - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onErrorHandler = (error: CometChat.CometChatException) => { - console.log("Error"); -}; - -return ; +function GroupMembersWithLongPress({ group }: { group: CometChat.Group }) { + return ( + { + console.log("Long pressed:", member.getName()); + }} + /> + ); +} ``` - - - - -*** - -### Filters - -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. +#### onBack -##### 1. GroupsRequestBuilder +Fires when the back button in the app bar is pressed. Requires `showBackButton={true}`. -The [GroupMembersRequestBuilder](/sdk/react-native/retrieve-group-members) enables you to filter and customize the group members list based on available parameters in GroupMembersRequestBuilder. This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupMembersRequestBuilder](/sdk/react-native/retrieve-group-members) - -| Methods | Type | Description | -| -------------------- | -------------- | ------------------------------------------------------------------------------------------------- | -| **setLimit** | number | sets the number of group members that can be fetched in a single request, suitable for pagination | -| **setSearchKeyword** | string | used for fetching group members matching the passed string | -| **setScopes** | Array\ | used for fetching group members based on multiple scopes | - -**Example** - -In the example below, we are applying a filter to the Group List based on limit and scope. - - - -```tsx -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { CometChatGroupsMembers } from "@cometchat/chat-uikit-react-native"; - -function App(): React.JSX.Element { - const [group, setGroup] = useState(undefined); - let groupMemberRequestBuilder; - - const getGroup = async () => { - const group = await CometChat.getGroup("mrc-uid"); - groupMemberRequestBuilder = new CometChat.GroupMembersRequestBuilder( - group.getGuid() - ).setScopes(["admin"]); - setGroup(group); - }; - - useEffect(() => { - //login - getGroup(); - }); - - const onErrorHandler = (error: CometChat.CometChatException) => { - //code - }; +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; +function GroupMembersWithBack({ group }: { group: CometChat.Group }) { return ( - <> - {group && ( - - )} - + { + console.log("Back pressed"); + }} + /> ); } ``` - +#### onSelection - +Fires when members are selected/deselected in selection mode. Requires `selectionMode` to be set. -*** - -##### 2. SearchRequestBuilder - -The SearchRequestBuilder uses [GroupMembersRequestBuilder](/sdk/react-native/retrieve-group-members) enables you to filter and customize the search list based on available parameters in GroupMembersRequestBuilder. This feature allows you to keep uniformity between the displayed Group Members List and searched Group Members List. - -**Example** +```tsx lines +onSelection?: (list: CometChat.GroupMember[]) => void +``` - - -```tsx +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { CometChatGroupsMembers } from "@cometchat/chat-uikit-react-native"; -function App(): React.JSX.Element { - const [group, setGroup] = useState(undefined); - let searchRequestBuilder; - - const getGroup = async () => { - const group = await CometChat.getGroup("mrc-uid"); - searchRequestBuilder = new CometChat.GroupMembersRequestBuilder( - group.getGuid() - ) - .setScopes(["admin"]) - .setSearchKeyword("some-search-keyword"); - setGroup(group); +function GroupMembersWithSelection({ group }: { group: CometChat.Group }) { + const handleSelection = (list: CometChat.GroupMember[]) => { + console.log("Selected:", list.length); }; - useEffect(() => { - //login - getGroup(); - }); - return ( - <> - {group && ( - - )} - + ); } ``` - +#### onSubmit - +Fires when the submit selection button is pressed. Requires `selectionMode` to be set. -*** +```tsx lines +onSubmit?: (list: Array) => void +``` -### Events +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +function GroupMembersWithSubmit({ group }: { group: CometChat.Group }) { + const handleSubmit = (list: Array) => { + console.log("Submit", list); + }; -Events emitted by the Group Members component is as follows. + return ; +} +``` -| Event | Description | -| ----------------------------- | ----------------------------------------------------------------- | -| **ccGroupMemberBanned** | Triggers when the group member banned from the group successfully | -| **ccGroupMemberKicked** | Triggers when the group member kicked from the group successfully | -| **ccGroupMemberScopeChanged** | Triggers when the group member scope is changed in the group | +#### onError - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +Fires on internal errors (network failure, auth issue, SDK exception). -CometChatUIEventHandler.addGroupListener("GROUP_LISTENER_ID", { - ccGroupMemberBanned: ({ - message, - kickedUser, - kickedBy, - kickedFrom, - }: { - message: CometChat.BaseMessage, - kickedUser: CometChat.User, - kickedBy: CometChat.User, - kickedFrom: CometChat.Group, - }) => { - //code - }, - ccGroupMemberKicked: ({ - message, - kickedFrom, - }: { - message: CometChat.BaseMessage, - kickedFrom: CometChat.Group, - }) => { - //code - }, - ccGroupMemberScopeChanged: ({ - action, - updatedUser, - scopeChangedTo, - scopeChangedFrom, - group, - }) => { - //code - }, -}); +```tsx lines +onError?: () => void ``` - +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; - +function GroupMembersWithError({ group }: { group: CometChat.Group }) { + return ( + { + console.error("CometChatGroupMembers error occurred"); + }} + /> + ); +} +``` -*** +#### onLoad - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +Fires when the list is successfully fetched and loaded. -CometChatUIEventHandler.removeGroupListener("GROUP_LISTENER_ID"); +```tsx lines +onLoad?: (list: CometChat.GroupMember[]) => void ``` - - - +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -*** +function GroupMembersWithLoad({ group }: { group: CometChat.Group }) { + const handleLoad = (list: CometChat.GroupMember[]) => { + console.log("Loaded members:", list.length); + }; -## Customization + return ; +} +``` -To fit your app's design requirements, you can customize the appearance of the Groups component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +#### onEmpty -### Style +Fires when the member list is empty. -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +```tsx lines +onEmpty?: () => void +``` - - - +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; - - -```tsx -import { - CometChatGroupMembers, - useTheme, -} from "@cometchat/chat-uikit-react-native"; -//other imports -const theme: CometChatTheme = useTheme(); -//code -return ( - group && ( +function GroupMembersWithEmpty({ group }: { group: CometChat.Group }) { + return ( { + console.log("No group members found"); }} /> - ) -); + ); +} ``` - +### Global UI Events - +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Add listeners and remove them on cleanup. -*** +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupMemberKicked` | A member is kicked from the group | `IGroupMemberKickedBanned` | +| `ccGroupMemberBanned` | A member is banned from the group | `IGroupMemberKickedBanned` | +| `ccGroupMemberScopeChanged` | A member's scope is changed | `IGroupMemberScopeChanged` | -### Functionality +When to use: sync external UI with group member state changes. For example, update a member list when a member is kicked, or refresh the UI when a member's scope changes. -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can toggle the visibility of UI elements. +```tsx lines +import { useEffect } from "react"; +import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -Below is a list of customizations along with corresponding code snippets +function useGroupMemberEvents() { + useEffect(() => { + const listenerId = "GROUP_MEMBER_EVENTS_" + Date.now(); + + CometChatUIEventHandler.addGroupListener(listenerId, { + ccGroupMemberKicked: ({ + message, + kickedFrom, + }: { + message: CometChat.BaseMessage; + kickedFrom: CometChat.Group; + }) => { + console.log("Member kicked from:", kickedFrom.getName()); + }, + ccGroupMemberBanned: ({ + message, + kickedUser, + kickedBy, + kickedFrom, + }: { + message: CometChat.BaseMessage; + kickedUser: CometChat.User; + kickedBy: CometChat.User; + kickedFrom: CometChat.Group; + }) => { + console.log("Member banned:", kickedUser.getName()); + }, + ccGroupMemberScopeChanged: ({ + action, + updatedUser, + scopeChangedTo, + scopeChangedFrom, + group, + }) => { + console.log("Scope changed:", updatedUser.getName(), "to", scopeChangedTo); + }, + }); + + return () => { + CometChatUIEventHandler.removeGroupListener(listenerId); + }; + }, []); +} +``` -| Property | Description | Code | -| ------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------ | -| **showBackButton** | Used to show or hide back button | `showBackButton={true}?: boolean` | -| **hideError** | Used to hide error on fetching groups | `hideError?: boolean` | -| **hideSearch** | Used to toggle visibility for search box | `hideSearch?: boolean` | -| **searchPlaceholderText** | Used to set custom search placeholder text | `searchPlaceholderText='Custom Search PlaceHolder'` | -| **selectionMode** | set the number of group members that can be selected, SelectionMode can be single, multiple or none. | `selectionMode?: 'none'` \| `'single'` \| `'multiple'` | -| **group** | Used to pass group object of which group members will be shown | `group: CometChat.Group` | -| **hideHeader** | Used to toggle visibility for the toolbar/header | `hideHeader?: boolean` | +### SDK Events (Real-Time, Automatic) -*** +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -### Advanced +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberScopeChanged` | Updates the member's scope in the list | +| `onGroupMemberKicked` | Removes the kicked member from the list | +| `onGroupMemberBanned` | Removes the banned member from the list | +| `onMemberAddedToGroup` | Appends the new member to the list | +| `onGroupMemberLeft` | Removes the member who left from the list | +| `onGroupMemberJoined` | Appends the joined member to the list | -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your own views, layouts, and UI elements and then incorporate those into the component. + +In React 18 StrictMode, `useEffect` runs twice on mount in development. The component handles listener cleanup internally, but any additional listeners added alongside the component need cleanup in the `useEffect` return function to avoid duplicate event handling. + -The `Group Memebers` component does not provide additional functionalities beyond this level of customization. +--- -*** +## Custom View Slots -#### LoadingView +Each slot replaces a section of the default UI. Slots that accept a member parameter receive the `CometChat.GroupMember` object for that row. -Displays a custom loading view while group members are being fetched. +| Slot | Signature | Replaces | +| --- | --- | --- | +| `ItemView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Entire list item row | +| `LeadingView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Avatar / left section | +| `TitleView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Name / title text | +| `SubtitleView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Subtitle text | +| `TrailingView` | `(groupMember: CometChat.GroupMember) => JSX.Element` | Right section (scope badge / actions) | +| `LoadingView` | `() => JSX.Element` | Loading spinner | +| `EmptyView` | `() => JSX.Element` | Empty state | +| `ErrorView` | `() => JSX.Element` | Error state | +| `AppBarOptions` | `() => JSX.Element` | Header bar options | -Use Cases: +### LoadingView -* Show a loading spinner with "Fetching group members...". -* Implement a skeleton loader for a smoother UI experience. +Custom view displayed when data is being fetched. - - -```tsx -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -//code -const getLoadingView = (): JSX.Element => { - //your custom loading view - //return jsx; -}; -return ( - -); +```tsx lines +LoadingView?: () => JSX.Element ``` - - - +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -*** +const getLoadingView = (): JSX.Element => { + return Loading group members...; +}; -#### EmptyView +return ; +``` -Configures a view to be displayed when no group members are found. +### EmptyView -Use Cases: +Custom view displayed when there are no group members. -* Display a message like "No members in this group yet.". -* Show a button to Invite Members. +```tsx lines +EmptyView?: () => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -//code + const getEmptyView = (): JSX.Element => { - //your custom Empty view - //return jsx; + return No members in this group yet.; }; -return ( - -); -``` - - - - -*** - -#### ErrorView +return ; +``` -Defines a custom error state view when there is an issue loading group members. +### ErrorView -Use Cases: +Custom view displayed when an error occurs. -* Display a retry button with "Failed to load members. Tap to retry.". -* Show an illustration for a better user experience. +```tsx lines +ErrorView?: () => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -//code + const getErrorView = (): JSX.Element => { - //your custom Error view - //return jsx; + return Failed to load members. Please try again.; }; -return ( - -); -``` - - - - -*** - -#### LeadingView +return ; +``` -Sets a custom leading view for each group member item, usually used for profile images or avatars. +### LeadingView -Use Cases: +Custom view for the avatar / left section of each member item. -* Show a circular avatar with an online/offline indicator. -* Add a role-based badge (Admin, Moderator, Member). +```tsx lines +LeadingView?: (groupMember: CometChat.GroupMember) => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code + const getLeadingView = (groupMember: CometChat.GroupMember): JSX.Element => { - //your custom Leading view - //return jsx; + return ( + + + {groupMember.getName().charAt(0)} + + + ); }; -return ( - -); -``` - - - - -*** - -#### TitleView +return ; +``` -Customizes the title view, typically displaying the member's name. +### TitleView -Use Cases: +Custom view for the name / title text. -* Customize fonts, colors, or styles for usernames. -* Add role-specific indicators like "(Group Admin)". +```tsx lines +TitleView?: (groupMember: CometChat.GroupMember) => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code + const getTitleView = (groupMember: CometChat.GroupMember): JSX.Element => { - //your custom title view - //return jsx; + return ( + + {groupMember.getName()} + + ); }; -return ( - -); -``` - - - - - -*** -#### ItemView - -Assigns a fully custom ListItem layout to the Group Members Component, replacing the default structure. - -Use Cases: - -* Include additional member details like joined date, bio, or status. -* Modify layout based on user roles. - - - -```tsx -import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getItemView = (groupMember: CometChat.GroupMember): JSX.Element => { - //your custom item view - //return jsx; -}; -return ( - -); +return ; ``` - +### SubtitleView - +Custom view for the subtitle text. -**Example** +```tsx lines +SubtitleView?: (groupMember: CometChat.GroupMember) => JSX.Element +``` - + -*** - -#### SubtitleView - -Customizes the subtitle view for each group member, typically used for extra details. - -Use Cases: - -* Show "Last Active" time. -* Display a custom status message. - - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code + const getSubtitleView = (groupMember: CometChat.GroupMember): JSX.Element => { - //your custom Subtitle view - //return jsx; + return ( + + {groupMember.getScope()} + + ); }; -return ( - -); + +return ; ``` - +### TrailingView - +Custom view for the right section (scope badge / actions). -**Example** +```tsx lines +TrailingView?: (groupMember: CometChat.GroupMember) => JSX.Element +``` - + -*** - -#### TrailingView - -Customizes the trailing (right-end) section of each member item, typically used for action buttons. - -Use Cases: - -* Show quick actions like Mute, Remove, or Promote. -* Display a "Last Active" timestamp. - - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code + const getTrailingView = (groupMember: CometChat.GroupMember): JSX.Element => { - //your custom Trailing view - //return jsx; + return ( + { /* action */ }}> + {groupMember.getScope()} + + ); }; -return ( - -); + +return ; ``` - +### ItemView - +Custom view for the entire list item row. -**Example** +```tsx lines +ItemView?: (groupMember: CometChat.GroupMember) => JSX.Element +``` - + -#### AppBarOptions +```tsx lines +import { + CometChatGroupMembers, + CometChatAvatar, + useTheme, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const theme = useTheme(); + +const getItemView = (groupMember: CometChat.GroupMember): JSX.Element => { + return ( + + + + + {groupMember.getName()} + + + {groupMember.getScope()} + + + + ); +}; + +return ; +``` -Allows customization of the overflow menu (three-dot ⋮ icon) with additional options. +### AppBarOptions -Use Cases: +Custom view for the header bar options. -* Add extra actions like "Report Member", "Restrict from Posting". -* Provide group admins with moderation options. +```tsx lines +AppBarOptions?: () => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTrailingView = (groupMember: CometChat.GroupMember): JSX.Element => { - //your custom Trailing view - //return jsx; -}; + return ( { return ( - { - //do something - }} - > + { /* handle click */ }}> Custom App Bar Options ); @@ -781,73 +771,161 @@ return ( ); ``` - - - +### options -#### options +Custom context menu actions for each member item. -Defines a set of available actions that users can perform when they interact with a group member item. +```tsx lines +options?: (groupMember: CometChat.GroupMember, group: CometChat.Group) => MenuItemInterface[] +``` -* Provide actions like "View Profile", "Send Message", "Remove from Group". -* Restrict certain actions to admins (e.g., "Promote to Admin", "Ban User"). +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -By customizing these options, developers can provide a streamlined and contextually relevant user experience +const setMyOptions = (member: CometChat.GroupMember, group: CometChat.Group) => { + return [ + { + text: "View Profile", + onPress: () => { /* view profile logic */ }, + }, + { + text: "Remove", + onPress: () => { /* remove logic */ }, + }, + ]; +}; - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code +return ; +``` -const setMyOptions = (_member: any, _group: any) => { - return [ - //options - ]; - }; +### addOptions +Extends the default context menu actions with additional options. -return ( - -); +```tsx lines +addOptions?: (groupMember: CometChat.GroupMember, group: CometChat.Group) => MenuItemInterface[] ``` - +```tsx lines +import { CometChatGroupMembers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; - +const addOptions = (member: CometChat.GroupMember, group: CometChat.Group) => { + return [ + { + text: "Report Member", + onPress: () => { /* report logic */ }, + }, + ]; +}; -#### addOptions +return ; +``` -This method extends the existing set of actions available when users long press a group item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: +--- -* Adding a "Report Spam" action -* Introducing a "Save to Notes" option -* Integrating third-party actions such as "Share to Cloud Storage" +## Styling -This method provides flexibility in modifying user interaction capabilities. +Using Style you can customize the look and feel of the component in your app. Pass a styling object as a prop to the `CometChatGroupMembers` component. - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code + + + -const addOptions = (_member: any, _group: any) => { - return [ - //options - ]; - }; +```tsx lines +import { + CometChatGroupMembers, + useTheme, +} from "@cometchat/chat-uikit-react-native"; +const theme = useTheme(); return ( ); ``` - +### Visibility Props + +| Property | Description | Code | +| --- | --- | --- | +| `hideHeader` | Toggle visibility for the toolbar/header | `hideHeader?: boolean` | +| `showBackButton` | Toggle visibility for back button | `showBackButton?: boolean` | +| `hideSearch` | Toggle visibility for search box | `hideSearch?: boolean` | +| `hideError` | Hide error on fetching group members | `hideError?: boolean` | +| `hideLoadingState` | Toggle visibility for Loading state | `hideLoadingState?: boolean` | +| `usersStatusVisibility` | Toggle visibility for user status indicators | `usersStatusVisibility?: boolean` | +| `hideKickMemberOption` | Hide the "Remove" (Kick) option from the default menu | `hideKickMemberOption?: boolean` | +| `hideBanMemberOption` | Hide the "Ban" option from the default menu | `hideBanMemberOption?: boolean` | +| `hideScopeChangeOption` | Hide the "Change Scope" option from the default menu | `hideScopeChangeOption?: boolean` | +| `excludeOwner` | Exclude the group owner from the members list | `excludeOwner?: boolean` | + +### Selection Mode + +| Property | Description | Code | +| --- | --- | --- | +| `selectionMode` | Determines the selection mode for group members | `selectionMode?: SelectionMode` | +| `searchKeyword` | Keyword used to fetch initial member list | `searchKeyword?: string` | +| `searchPlaceholderText` | Placeholder text for search input | `searchPlaceholderText?: string` | + +--- - +## Next Steps + + + + Display and manage group conversations + + + Add new members to a group + + + View and manage banned group members + + + Customize the appearance of UI Kit components + + diff --git a/ui-kit/react-native/groups.mdx b/ui-kit/react-native/groups.mdx index 4b8045e24..1dbeca2bc 100644 --- a/ui-kit/react-native/groups.mdx +++ b/ui-kit/react-native/groups.mdx @@ -1,687 +1,1065 @@ --- title: "Groups" +description: "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator." --- + +```json +{ + "component": "CometChatGroups", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatGroups } from \"@cometchat/chat-uikit-react-native\";", + "description": "Searchable, scrollable list of all available groups with icon, name, member count, and group type indicator.", + "primaryOutput": { + "prop": "onItemPress", + "type": "(group: CometChat.Group) => void" + }, + "props": { + "data": { + "groupsRequestBuilder": { + "type": "CometChat.GroupsRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "searchRequestBuilder": { + "type": "CometChat.GroupsRequestBuilder", + "default": "undefined" + }, + "searchKeyword": { + "type": "string", + "default": "\"\"" + } + }, + "callbacks": { + "onItemPress": "(group: CometChat.Group) => void", + "onItemLongPress": "(group: CometChat.Group) => void", + "onBack": "() => void", + "onSelection": "(list: Array) => void", + "onSubmit": "(list: Array) => void", + "onError": "(error: CometChat.CometChatException) => void", + "onEmpty": "() => void", + "onLoad": "(list: CometChat.GroupMember[]) => void" + }, + "visibility": { + "hideHeader": { "type": "boolean", "default": false }, + "showBackButton": { "type": "boolean", "default": false }, + "hideSearch": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "hideSubmitButton": { "type": "boolean", "default": true }, + "hideLoadingState": { "type": "boolean", "default": false }, + "groupTypeVisibility": { "type": "boolean", "default": true } + }, + "icons": { + "privateGroupIcon": { "type": "ImageSourcePropType", "default": "built-in" }, + "passwordGroupIcon": { "type": "ImageSourcePropType", "default": "built-in" } + }, + "menu": { + "options": "(group: CometChat.Group) => MenuItemInterface[]", + "addOptions": "(group: CometChat.Group) => MenuItemInterface[]" + }, + "search": { + "searchPlaceholderText": { "type": "string", "default": "\"Search\"" } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["single", "multiple", "none"], + "default": "none" + } + }, + "viewSlots": { + "ItemView": "(group: CometChat.Group) => JSX.Element", + "LeadingView": "(group: CometChat.Group) => JSX.Element", + "TitleView": "(group: CometChat.Group) => JSX.Element", + "SubtitleView": "(group: CometChat.Group) => JSX.Element", + "TrailingView": "(group: CometChat.Group) => JSX.Element", + "LoadingView": "() => JSX.Element", + "EmptyView": "() => JSX.Element", + "ErrorView": "() => JSX.Element", + "AppBarOptions": "() => JSX.Element" + } + }, + "events": [ + { "name": "ccGroupCreated", "payload": "CometChat.Group", "description": "Triggered when logged-in user creates a group" }, + { "name": "ccGroupDeleted", "payload": "CometChat.Group", "description": "Triggered when logged-in user deletes a group" }, + { "name": "ccGroupLeft", "payload": "{ leftGroup: CometChat.Group }", "description": "Triggered when logged-in user leaves a group" }, + { "name": "ccGroupMemberScopeChanged", "payload": "IGroupMemberScopeChanged", "description": "Triggered when logged-in user changes scope of another member" }, + { "name": "ccGroupMemberBanned", "payload": "IGroupMemberKickedBanned", "description": "Triggered when logged-in user bans a group member" }, + { "name": "ccGroupMemberKicked", "payload": "IGroupMemberKickedBanned", "description": "Triggered when logged-in user kicks a group member" }, + { "name": "ccGroupMemberUnbanned", "payload": "IGroupMemberUnBanned", "description": "Triggered when logged-in user unbans a group member" }, + { "name": "ccGroupMemberJoined", "payload": "IGroupMemberJoined", "description": "Triggered when logged-in user joins a group" }, + { "name": "ccGroupMemberAdded", "payload": "IGroupMemberAdded", "description": "Triggered when logged-in user adds members to a group" }, + { "name": "ccOwnershipChanged", "payload": "IOwnershipChanged", "description": "Triggered when logged-in user transfers group ownership" } + ], + "sdkListeners": [ + "onGroupMemberJoined", + "onGroupMemberLeft", + "onMemberAddedToGroup", + "onGroupMemberKicked", + "onGroupMemberBanned", + "onGroupMemberScopeChanged" + ], + "compositionExample": { + "description": "Group directory wired to message view", + "components": [ + "CometChatGroups", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemPress emits CometChat.Group -> pass to MessageHeader, MessageList, MessageComposer" + }, + "types": { + "SelectionMode": { + "single": "Select one group at a time", + "multiple": "Select multiple groups", + "none": "No selection mode" + } + } +} +``` + + +## Where It Fits + +`CometChatGroups` is a directory list component. It renders all available groups and emits the selected `CometChat.Group` via `onItemPress`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a group chat layout. + +```tsx lines +import { useState } from "react"; +import { View, Text, StyleSheet } from "react-native"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { + CometChatGroups, + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatThemeProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -## Overview +function ChatApp() { + const [selectedGroup, setSelectedGroup] = useState(); -`CometChatGroups` functions as a standalone [Component](/ui-kit/react-native/components-overview#components), showcasing an accessible list of all available groups. It provides an integral search functionality, allowing you to locate any specific groups swiftly and easily. For each group listed, the group name is displayed by default, in conjunction with the group icon when available. Additionally, it provides a useful feature by displaying the number of members in each group as a subtitle, offering valuable context about group size and activity level. + return ( + + + + + + setSelectedGroup(group)} /> + + {selectedGroup ? ( + + + + + + ) : ( + + Select a group + + )} + + + + + ); +} + +const styles = StyleSheet.create({ + container: { flex: 1, flexDirection: "row" }, + sidebar: { width: 350 }, + chatArea: { flex: 1 }, + placeholder: { flex: 1, justifyContent: "center", alignItems: "center" }, +}); +``` -*** +--- -## Usage +## Minimal Render -*** +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -### Integration +function GroupsDemo() { + return ; +} + +export default GroupsDemo; +``` + +--- + +## Filtering Groups -The following code snippet illustrates how you can can launch `CometChatGroups`. +Pass a `CometChat.GroupsRequestBuilder` to `groupsRequestBuilder`. Pass the builder instance — not the result of `.build()`. -```tsx App.tsx +```tsx lines import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -return ; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function FilteredGroups() { + return ( + + ); +} ``` -*** +### Filter Recipes + +| Recipe | Code | +| --- | --- | +| Joined groups only | `new CometChat.GroupsRequestBuilder().joinedOnly(true)` | +| Limit to 10 per page | `new CometChat.GroupsRequestBuilder().setLimit(10)` | +| Search by keyword | `new CometChat.GroupsRequestBuilder().setSearchKeyword("design")` | +| Filter by tags | `new CometChat.GroupsRequestBuilder().setTags(["vip"])` | +| With tags data | `new CometChat.GroupsRequestBuilder().withTags(true)` | + +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. -### Actions +A separate `searchRequestBuilder` can be passed to filter the search list independently from the main list. -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and Group-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +Refer to [GroupsRequestBuilder](/sdk/react-native/retrieve-groups) for the full builder API. -##### onItemPress +--- + +## Actions and Events + +### Callback Props + +#### onItemPress -Function invoked when a Group item is clicked, typically used to open a Group profile or chat screen. +Fires when a group row is tapped. Primary navigation hook — set the active group and render the message view. - - -```tsx +```tsx lines import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onPressHandler = (user: CometChat.Group) => { - //code -}; +function GroupsWithPress() { + const handleItemPress = (group: CometChat.Group) => { + console.log("Selected:", group.getName()); + }; -return ; + return ; +} ``` - +#### onItemLongPress + +Fires when a group item is long-pressed, allowing additional actions like leave or delete. + +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; - +function GroupsWithLongPress() { + const handleLongPress = (group: CometChat.Group) => { + console.log("Long pressed:", group.getName()); + }; -*** + return ; +} +``` -##### onItemLongPress +#### onSelection -Function executed when a Group item is long-pressed, allowing additional actions like delete or block. +Fires when groups are selected/deselected in selection mode. Requires `selectionMode` to be set. - - -```tsx +```tsx lines import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onLongPressHandler = (user: CometChat.Group) => { - //code -}; +function GroupsWithSelection() { + const handleSelection = (list: Array) => { + console.log("Selected:", list.length); + }; -return ; + return ( + + ); +} ``` - +#### onEmpty - +Fires when the group list fetch returns zero results. -*** +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -##### onBack +function GroupsWithEmptyHandler() { + return ( + console.log("No groups available")} /> + ); +} +``` -`onBack` is triggered when you press the back button in the app bar. It has a predefined behavior; when clicked, it navigates to the previous activity. However, you can override this action using the following code snippet. +#### onError - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +Fires on internal errors (network failure, auth issue, SDK exception). -const onBackHandler = () => { - //code -}; +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -return ; +function GroupsWithErrorHandler() { + return ( + { + console.error("CometChatGroups error:", error); + }} + /> + ); +} ``` - +#### onLoad - +Fires when groups are successfully fetched and loaded. -*** +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -##### onSelection +function GroupsWithLoadHandler() { + const handleLoad = (list: CometChat.GroupMember[]) => { + console.log("Groups loaded:", list.length); + }; -Called when a item from the fetched list is selected, useful for multi-selection features. + return ; +} +``` - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +### Global UI Events + +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Subscribe in a `useEffect` and unsubscribe on cleanup. + +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccGroupCreated` | The logged-in user creates a group | `CometChat.Group` | +| `ccGroupDeleted` | The logged-in user deletes a group | `CometChat.Group` | +| `ccGroupLeft` | The logged-in user leaves a group | `{ leftGroup: CometChat.Group }` | +| `ccGroupMemberScopeChanged` | The logged-in user changes scope of another member | `IGroupMemberScopeChanged` | +| `ccGroupMemberBanned` | The logged-in user bans a group member | `IGroupMemberKickedBanned` | +| `ccGroupMemberKicked` | The logged-in user kicks a group member | `IGroupMemberKickedBanned` | +| `ccGroupMemberUnbanned` | The logged-in user unbans a group member | `IGroupMemberUnBanned` | +| `ccGroupMemberJoined` | The logged-in user joins a group | `IGroupMemberJoined` | +| `ccGroupMemberAdded` | The logged-in user adds members to a group | `IGroupMemberAdded` | +| `ccOwnershipChanged` | The logged-in user transfers group ownership | `IOwnershipChanged` | + +```tsx lines +import { useEffect } from "react"; +import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onSelectionHandler = (selection: Array) => { - //code -}; +function useGroupEvents() { + useEffect(() => { + const listenerId = "GROUP_EVENTS_" + Date.now(); + + CometChatUIEventHandler.addGroupListener(listenerId, { + ccGroupCreated: (group: CometChat.Group) => { + console.log("Group created:", group.getName()); + }, + ccGroupDeleted: (group: CometChat.Group) => { + console.log("Group deleted:", group.getName()); + }, + ccGroupLeft: ({ leftGroup }: { leftGroup: CometChat.Group }) => { + console.log("Left group:", leftGroup.getName()); + }, + }); -return ( - -); + return () => { + CometChatUIEventHandler.removeGroupListener(listenerId); + }; + }, []); +} ``` - +### SDK Events (Real-Time, Automatic) + +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. + +| SDK Listener | Internal behavior | +| --- | --- | +| `onGroupMemberJoined` | Updates member count when a user joins | +| `onGroupMemberLeft` | Updates member count when a user leaves | +| `onMemberAddedToGroup` | Updates member count when members are added | +| `onGroupMemberKicked` | Updates member count when a member is kicked | +| `onGroupMemberBanned` | Updates member count when a member is banned | +| `onGroupMemberScopeChanged` | Updates scope when a member's scope changes | + +--- - +## Custom View Slots + +Each slot replaces a section of the default UI. Slots that accept a group parameter receive the `CometChat.Group` object for that row. + +| Slot | Signature | Replaces | +| --- | --- | --- | +| `ItemView` | `(group: CometChat.Group) => JSX.Element` | Entire list item row | +| `LeadingView` | `(group: CometChat.Group) => JSX.Element` | Avatar / left section | +| `TitleView` | `(group: CometChat.Group) => JSX.Element` | Name / title text | +| `SubtitleView` | `(group: CometChat.Group) => JSX.Element` | Member count subtitle | +| `TrailingView` | `(group: CometChat.Group) => JSX.Element` | Right section | +| `LoadingView` | `() => JSX.Element` | Loading spinner | +| `EmptyView` | `() => JSX.Element` | Empty state | +| `ErrorView` | `() => JSX.Element` | Error state | +| `AppBarOptions` | `() => JSX.Element` | Header bar options | + +### ItemView + +Replace the entire list item row. + + + + + +```tsx lines +import { + CometChatGroups, + CometChatAvatar, + useTheme, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text } from "react-native"; + +function CustomItemViewGroups() { + const theme = useTheme(); + + const getItemView = (group: CometChat.Group) => { + return ( + + + + + {group.getName()} + + + {group.getMembersCount()} members + + + + ); + }; + + return ; +} +``` -*** +### SubtitleView -##### onError +Replace the member count subtitle. -This action doesn't change the behavior of the component but rather listens for any errors that occur in the groups component. + + + - - -```tsx +```tsx lines import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { Text } from "react-native"; + +function SubtitleViewGroups() { + const getSubtitleView = (group: CometChat.Group) => { + return ( + + {group.getMembersCount()} members • {group.getType()} + + ); + }; + + return ; +} +``` + +### AppBarOptions -const onErrorHandler = (error: CometChat.CometChatException) => { - console.log("Error"); -}; +Custom view for the header bar options. -return ; + + + + +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { TouchableOpacity, Text } from "react-native"; + +function AppBarOptionsGroups() { + return ( + ( + console.log("Create group")}> + + Create + + )} + /> + ); +} ``` - +### options - +Custom context menu actions for each group item. -*** +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -### Filters +function OptionsGroups() { + const getOptions = (group: CometChat.Group) => [ + { + text: "Leave", + onPress: () => console.log("Leave:", group.getName()), + }, + { + text: "Mute", + onPress: () => console.log("Mute:", group.getName()), + }, + ]; + + return ; +} +``` -Filters allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +--- -##### 1. GroupsRequestBuilder +## Common Patterns -The [GroupsRequestBuilder](/sdk/react-native/retrieve-groups) enables you to filter and customize the group list based on available parameters in [GroupsRequestBuilder](/sdk/react-native/retrieve-groups). This feature allows you to create more specific and targeted queries when fetching groups. The following are the parameters available in [GroupsRequestBuilder](/sdk/react-native/retrieve-groups) +### Custom empty state with CTA -| Methods | Type | Description | -| -------------------- | -------------- | --------------------------------------------------------------------------------------- | -| **setLimit** | number | sets the number groups that can be fetched in a single request, suitable for pagination | -| **setSearchKeyword** | string | used for fetching groups matching the passed string | -| **joinedOnly** | boolean | to fetch only joined groups | -| **friendsOnly** | boolean | used for fetching only those users in which logged in user is a member | -| **setTags** | Array\ | used for fetching groups containing the passed tags | -| **withTags** | boolean | used to fetch tags data along with the list of groups | +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { View, Text, TouchableOpacity } from "react-native"; -**Example** +function EmptyStateGroups() { + return ( + ( + + No groups found + console.log("Create group")}> + Create a group + + + )} + /> + ); +} +``` -In the example below, we are applying a filter to the Group List based on only joined groups and setting the limit to ten. +### Joined groups only - - -```tsx +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function JoinedGroupsOnly() { + return ( + + ); +} +``` + +### Multi-select with submit + +```tsx lines import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -function App(): React.JSX.Element { - const groupsRequestBuilder = new CometChat.GroupsRequestBuilder() - .setLimit(10) - .joinedOnly(true); +function MultiSelectGroups() { + const handleSubmit = (groups: Array) => { + console.log("Selected groups:", groups.length); + }; return ( ); } ``` - +### Hide all chrome — minimal list - +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -##### 2. SearchRequestBuilder +function MinimalGroups() { + return ( + + ); +} +``` -The SearchRequestBuilder uses [GroupsRequestBuilder](/sdk/react-native/retrieve-groups) enables you to filter and customize the search list based on available parameters in [GroupsRequestBuilder](/sdk/react-native/retrieve-groups). +--- -**Example** +## Styling - - -```tsx -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +The component uses the theme system from `CometChatThemeProvider`. Pass a `style` prop to customize the appearance. -function App(): React.JSX.Element { - const searchRequestBuilder = new CometChat.GroupsRequestBuilder() - .setLimit(10) - .setSearchKeyword("custom-keyword"); + + + + +```tsx lines +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +function StyledGroups() { return ( ); } ``` - +### Style Properties - +| Property | Type | Description | +| --- | --- | --- | +| `containerStyle` | `ViewStyle` | Style for the root container | +| `headerStyle` | `ViewStyle` | Style for the header section | +| `titleStyle` | `TextStyle` | Style for the header title | +| `itemStyle` | `object` | Style for list items (includes `avatarStyle`, `titleStyle`, `subtitleStyle`) | +| `searchStyle` | `object` | Style for the search bar | -*** +--- -### Events +## Props -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +All props are optional unless noted. -The list of events emitted by the Groups component is as follows. +### EmptyView -| Events | Description | -| --------------------------- | ---------------------------------------------------------------------------------------------------------- | -| `ccGroupCreated` | This will get triggered when the logged in user creates a group | -| `ccGroupDeleted` | This will get triggered when the logged in user deletes a group | -| `ccGroupLeft` | This will get triggered when the logged in user leaves a group | -| `ccGroupMemberScopeChanged` | This will get triggered when the logged in user changes the scope of another group member | -| `ccGroupMemberBanned` | This will get triggered when the logged in user bans a group member from the group | -| `ccGroupMemberKicked` | This will get triggered when the logged in user kicks another group member from the group | -| `ccGroupMemberUnbanned` | This will get triggered when the logged in user unbans a user banned from the group | -| `ccGroupMemberJoined` | This will get triggered when the logged in user joins a group | -| `ccGroupMemberAdded` | This will get triggered when the logged in user add new members to the group | -| `ccOwnershipChanged` | This will get triggered when the logged in user transfer the ownership of their group to some other member | +Custom component displayed when there are no groups. -##### 1. Add `CometChatGroupEvents` Listener's +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in empty state | - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +--- -CometChatUIEventHandler.addGroupListener("GROUP_LISTENER_ID", { - ccGroupLeft: ({ leftGroup }) => { - //code - }, -}); +### ErrorView -CometChatUIEventHandler.addGroupListener("GROUP_LISTENER_ID", { - ccGroupDeleted: ({ group }) => { - //code - }, -}); -``` +Custom component displayed when an error occurs. - +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in error state | - +--- -*** +### groupsRequestBuilder -##### 2. Removing `CometChatGroupEvents` Listener's +Controls which groups load and in what order. - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +| | | +| --- | --- | +| Type | `CometChat.GroupsRequestBuilder` | +| Default | SDK default (30 per page) | -CometChatUIEventHandler.removeGroupListener("GROUP_LISTENER_ID"); -``` +Pass the builder instance, not the result of `.build()`. - +--- - +### groupTypeVisibility -*** +Shows/hides the group type icon (public/private/password). -## Customization +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -To fit your app's design requirements, you can customize the appearance of the groups component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +--- -### Style +### hideError -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Hides the error state view. - - - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -return ( - -); -``` +--- - +### hideHeader - +Hides the entire header bar. -### Functionality +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +--- -Below is a list of customizations along with corresponding code snippets +### hideLoadingState -| Property | Description | Code | -| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | -| **hideHeader** | Used to toggle visibility for the toolbar/header | `hideHeader?: boolean` | -| **showBackButton** | Used to toggle visibility for back button | `showBackButton?: boolean` | -| **hideSearch** | Used to toggle visibility for search box | `hideSearch?: boolean` | -| **hideError** | Used to hide error on fetching users | `hideError?: boolean` | -| **selectionMode** | This method determines the selection mode for groups, enabling users to select either a single user or multiple groups at once. | `selectionMode='multiple'` | -| **hideSubmitButton** | Used to toggle the visibility of the submit button when selectionMode is enabled. | `hideSubmitButton={true}` | -| **searchPlaceholderText** | Used to set search placeholder text | `searchPlaceholderText=''` | +Hides the loading state while fetching groups. -*** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -### Advanced +--- -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +### hideSearch -#### LoadingView +Hides the search bar. -Configures a custom loading view displayed while groups are being fetched. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Use Cases: +--- -* Show a spinner with "Loading groups..." text. -* Display a skeleton loader for a smooth UI experience. +### hideSubmitButton - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getLoadingView = (): JSX.Element => { - //your custom loading view - //return jsx; -}; -return ; -``` +Hides the submit button when selection mode is enabled. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | - +--- -*** +### ItemView -#### EmptyView +Custom renderer for the entire list item row. -Defines a view that appears when no groups are available. +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in list item | -Use Cases: +--- -* Show a message like "No groups found, create one now!". -* Display an illustration with a "Create New Group" button. +### LeadingView - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getEmptyView = (): JSX.Element => { - //your custom empty view - //return jsx; -}; -return ; -``` +Custom renderer for the avatar / left section. - +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in avatar | - +--- -*** +### LoadingView -#### ErrorView +Custom component displayed during the loading state. -Configures the UI when an error occurs while fetching groups. +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in loading indicator | -Use Cases: +--- -* Display a retry button with "Failed to load groups, try again.". -* Show a friendly error illustration. +### onBack - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getErrorView = (): JSX.Element => { - //your custom error view - //return jsx; -}; -return ; -``` +Callback fired when the back button is pressed. - +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | - +--- -*** +### onEmpty -#### LeadingView +Callback fired when the group list is empty. -Sets a custom leading view that appears at the start of each group item. +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -Use Cases: +--- -* Display the group profile picture. -* Add an icon indicating Public or Private groups. +### onError - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getLeadingView = (item: CometChat.Group): JSX.Element => { - //your custom leading view - //return jsx; -}; -return ; -``` +Callback fired when the component encounters an error. - +| | | +| --- | --- | +| Type | `(error: CometChat.CometChatException) => void` | +| Default | `undefined` | - +--- -*** +### onItemLongPress -#### TitleView +Callback fired when a group row is long-pressed. -Customizes the title view of each group item, which typically displays the group name. +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => void` | +| Default | `undefined` | -Use Cases: +--- -* Style group names with custom fonts and colors. -* Show a verified badge for official groups. +### onItemPress - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getTitleView = (item: CometChat.Group): JSX.Element => { - //your custom title view - //return jsx; -}; -return ; -``` +Callback fired when a group row is tapped. - +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => void` | +| Default | `undefined` | - +--- -*** +### onLoad -#### TrailingView +Callback fired when groups are loaded. -Allows custom elements to be added at the end of each group item, such as buttons or indicators. +| | | +| --- | --- | +| Type | `(list: CometChat.GroupMember[]) => void` | +| Default | `undefined` | -Use Cases: +--- -* Show unread message counts. -* Add a quick Join or Leave button. +### onSelection - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getTrailingView = (item: CometChat.Group): JSX.Element => { - //your custom Trailing view - //return jsx; -}; -return ; -``` +Callback fired when groups are selected/deselected. Requires `selectionMode` to be set. - +| | | +| --- | --- | +| Type | `(list: Array) => void` | +| Default | `undefined` | - +--- -#### ItemView +### onSubmit -Assigns a fully custom ListItem layout to the Groups component, replacing the default design. +Callback fired when the submit button is pressed. Requires `selectionMode` to be set. -Use Cases: +| | | +| --- | --- | +| Type | `(list: Array) => void` | +| Default | `undefined` | -* Add a description below the group name. -* Customize layout to include additional metadata. +--- - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getItemView = (item: CometChat.Group): JSX.Element => { - //your custom Item view - //return jsx; -}; -return ; -``` +### searchKeyword - +Pre-fills the search and filters the group list. - +| | | +| --- | --- | +| Type | `string` | +| Default | `""` | -**Example** +--- - - - +### searchRequestBuilder -*** +Request builder with search parameters to fetch groups. -#### SubTitleView +| | | +| --- | --- | +| Type | `CometChat.GroupsRequestBuilder` | +| Default | `undefined` | -Customizes the subtitle view for each group item, which typically displays extra information. +--- -Use Cases: +### selectionMode -* Show last message preview. -* Display the number of members. +Enables single or multi-select mode on list items. - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -const getSubtitleView = (item: CometChat.Group): JSX.Element => { - //your custom Subtitle view - //return jsx; -}; -return ; -``` +| | | +| --- | --- | +| Type | `"single" \| "multiple" \| "none"` | +| Default | `"none"` | - +--- - +### showBackButton -**Example** +Shows the back button in the header. - - - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** +--- -#### AppBarOptions +### searchPlaceholderText -Customizes the overflow menu (three-dot ⋮ icon) with additional options. +Placeholder text for the search input. -Use Cases: +| | | +| --- | --- | +| Type | `string` | +| Default | `"Search"` | -* Add options like "Invite Members", "Report Group". -* Enable admin-specific options like "Manage Group Settings". +--- - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code -return ( - { - return ( - { - //do something - }} - > - Custom App Bar Options - - ); - }} - /> -); -``` +### privateGroupIcon - +Custom icon for private groups. - +| | | +| --- | --- | +| Type | `ImageSourcePropType` | +| Default | Built-in icon | -**Example** +--- - - - +### passwordGroupIcon + +Custom icon for password-protected groups. -#### options +| | | +| --- | --- | +| Type | `ImageSourcePropType` | +| Default | Built-in icon | -This method sets a predefined list of actions that users can perform when they long press a user in the list. These options typically include: +--- -* Enable actions like "Mute Notifications", "Leave Group", "Pin Group". -* Provide admin-only actions like "Manage Members", "Delete Group". +### addOptions -By customizing these options, developers can provide a streamlined and contextually relevant user experience +Function to append additional menu items to the default context menu. - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => MenuItemInterface[]` | +| Default | `undefined` | -const setMyOptions = (group: CometChat.Group) => { - return [ - //options - ]; - }; +--- +### options -return ( - -); -``` +Function to replace the default context menu items entirely. - +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => MenuItemInterface[]` | +| Default | `undefined` | - +--- -#### addOptions +### SubtitleView -This method extends the existing set of actions available when users long press a group item. Unlike setOptionsDefines, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: +Custom renderer for the member count subtitle. -* Adding a "Report Spam" action -* Introducing a "Save to Notes" option -* Integrating third-party actions such as "Share to Cloud Storage" +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in subtitle | -This method provides flexibility in modifying user interaction capabilities. +--- - - -```tsx -import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; -//code +### TitleView -const addOptions = (group: CometChat.Group) => { - return [ - //options - ]; - }; +Custom renderer for the name / title text. +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in title | -return ( - -); -``` +--- + +### TrailingView - +Custom renderer for the right section. + +| | | +| --- | --- | +| Type | `(group: CometChat.Group) => JSX.Element` | +| Default | Built-in trailing view | + +--- - +## Next Steps + + + + View and manage members of a group + + + Display and manage the list of recent chats + + + Display the full chat interface after selecting a group + + + Customize the appearance of UI Kit components + + \ No newline at end of file diff --git a/ui-kit/react-native/guide-ai-agent.mdx b/ui-kit/react-native/guide-ai-agent.mdx index e8b89fe33..200657a38 100644 --- a/ui-kit/react-native/guide-ai-agent.mdx +++ b/ui-kit/react-native/guide-ai-agent.mdx @@ -1,8 +1,22 @@ --- title: "AI Agent Integration" sidebarTitle: "AI Agent Integration" +description: "Enable intelligent conversational AI capabilities in your React Native app using CometChat UI Kit v5 with AI Agent integration." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key components | `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer`, `CometChatAIAssistantChatHistory` | +| Required setup | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Enable intelligent conversational AI capabilities with AI Agent integration | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/sample) | +| Related | [Message List](/ui-kit/react-native/message-list) · [Message Composer](/ui-kit/react-native/message-composer) · [All Guides](/ui-kit/react-native/guide-overview) | + + + Enable intelligent conversational AI capabilities in your React Native app using CometChat UIKit v5 with AI Agent integration: - **AI Assistant Chat History** @@ -50,6 +64,8 @@ The AI Agent chat interface provides a familiar messaging experience enhanced wi Create the AI Assistant chat screen with proper navigation and component configuration. + + ```tsx import React, { useState, useEffect } from 'react'; import { SafeAreaView, View } from 'react-native'; @@ -175,11 +191,15 @@ const AIGreetingView = () => ( export default AIAssistantChatScreen; ``` + + ### Step 2 - Navigation Setup Configure React Navigation to handle AI Assistant chat screens. + + ```tsx // App.tsx or your main navigation file import React from 'react'; @@ -225,11 +245,15 @@ const App = () => { export default App; ``` + + ### Step 3 - Theme Customization Define custom themes for the message list and composer to differentiate AI agent chats. + + ```tsx // AITheme.ts import { CometChatTheme } from '@cometchat/chat-uikit-react-native'; @@ -344,11 +368,15 @@ export const aiAssistantTheme: Partial = { }, }; ``` + + ### Step 4 - AI Assistant Tools Configuration -Configure AI Assistant tools and suggested messages for enhanced user experience. +Configure AI Assistant tools and suggested messages for an enhanced user experience. + + ```tsx // AIAssistantConfig.ts import { CometChat } from '@cometchat/chat-sdk-react-native'; @@ -414,11 +442,15 @@ export const EnhancedAIAssistantChatScreen: React.FC ); }; ``` + + ### Step 5 - Create AI Assistant Chat History Screen -Create a screen to host `CometChatAIAssistantChatHistory` component and handle its interactions. +Create a screen to host the `CometChatAIAssistantChatHistory` component and handle its interactions. + + ```tsx // AIAssistantChatHistoryScreen.tsx import React, { useState, useEffect } from 'react'; @@ -532,11 +564,15 @@ const AIAssistantChatHistoryScreen: React.FC export default AIAssistantChatHistoryScreen; ``` + + ### Step 6 - Launching AI Chat Create navigation functions to launch AI Assistant chat from your main application. + + ```tsx // MainChatScreen.tsx or your main component import React from 'react'; @@ -614,6 +650,8 @@ const MainChatScreen: React.FC = ({ navigation }) => { export default MainChatScreen; ``` + + ## Implementation Flow Summary @@ -649,4 +687,23 @@ export default MainChatScreen; Learn more about React Native UI Kit components: [GitHub → React Native UIKit](https://github.com/cometchat/cometchat-uikit-react-native) - \ No newline at end of file + + +--- + +## Next Steps + + + + Display and manage messages in a conversation + + + Compose and send messages with rich input options + + + Browse all feature and formatter guides + + + Explore all available components + + diff --git a/ui-kit/react-native/guide-block-unblock-user.mdx b/ui-kit/react-native/guide-block-unblock-user.mdx new file mode 100644 index 000000000..bdda57056 --- /dev/null +++ b/ui-kit/react-native/guide-block-unblock-user.mdx @@ -0,0 +1,329 @@ +--- +title: "Block/Unblock Users" +sidebarTitle: "Block/Unblock Users" +description: "Implement block and unblock user functionality in CometChat React Native UI Kit with composer state management." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key methods | `CometChat.blockUsers()`, `CometChat.unblockUsers()` | +| Init | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Events | `CometChatUIEvents.ccUserBlocked`, `CometChatUIEvents.ccUserUnBlocked` | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleApp) | +| Related | [Users](/ui-kit/react-native/users) · [Message Composer](/ui-kit/react-native/message-composer) · [All Guides](/ui-kit/react-native/guide-overview) | + + + +Block/Unblock lets users prevent specific users from sending them messages. When blocked, the message composer is hidden and replaced with an unblock prompt. + +Before starting, complete the [Getting Started](/ui-kit/react-native/react-native-cli-integration) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChat.blockUsers()` | SDK method to block specific users | +| `CometChat.unblockUsers()` | SDK method to unblock previously blocked users | +| `CometChatUIEvents.ccUserBlocked` | Event fired when a user is blocked | +| `CometChatUIEvents.ccUserUnBlocked` | Event fired when a user is unblocked | +| `CometChatConfirmDialog` | Confirmation dialog for block/unblock actions | + +--- + +## Integration Steps + + +### 1. Block User + +Call `CometChat.blockUsers()` with the target UID. On success, emit `ccUserBlocked` so all subscribed components react to the change. + +```tsx +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatUIEventHandler, + CometChatUIEvents, +} from '@cometchat/chat-uikit-react-native'; + +const blockUser = async (user: CometChat.User) => { + try { + const uid = user.getUid(); + await CometChat.blockUsers([uid]); + + // Fetch fresh user data + const freshUser = await CometChat.getUser(uid); + + // Emit event so UI components update + CometChatUIEventHandler.emitUserEvent( + CometChatUIEvents.ccUserBlocked, + { user: freshUser } + ); + + console.log('User blocked successfully'); + } catch (error) { + console.error('Blocking user failed:', error); + } +}; +``` + +--- + +### 2. Unblock User + +Call `CometChat.unblockUsers()` with the target UID. On success, emit `ccUserUnBlocked` to restore the composer. + +```tsx +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatUIEventHandler, + CometChatUIEvents, +} from '@cometchat/chat-uikit-react-native'; + +const unblockUser = async (user: CometChat.User) => { + try { + const uid = user.getUid(); + await CometChat.unblockUsers([uid]); + + // Fetch fresh user data + const freshUser = await CometChat.getUser(uid); + + // Emit event so UI components update + CometChatUIEventHandler.emitUserEvent( + CometChatUIEvents.ccUserUnBlocked, + { user: freshUser } + ); + + console.log('User unblocked successfully'); + } catch (error) { + console.error('Unblocking user failed:', error); + } +}; +``` + +--- + +### 3. Composer Blocked State + +When a user is blocked, replace the composer with an unblock prompt. + +```tsx +import React, { useState, useEffect } from 'react'; +import { View, Text, TouchableOpacity } from 'react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatMessageComposer, + CometChatUIEventHandler, + CometChatUIEvents, + useTheme, + useCometChatTranslation, +} from '@cometchat/chat-uikit-react-native'; + +interface MessageComposerWithBlockProps { + user: CometChat.User; +} + +const MessageComposerWithBlock: React.FC = ({ user }) => { + const theme = useTheme(); + const { t } = useCometChatTranslation(); + const [localUser, setLocalUser] = useState(user); + + // Listen for block/unblock events + useEffect(() => { + const listenerId = 'composer_block_listener_' + Date.now(); + + CometChatUIEventHandler.addUserListener(listenerId, { + ccUserBlocked: (payload: { user: CometChat.User }) => { + if (payload.user.getUid() === localUser.getUid()) { + setLocalUser(payload.user); + } + }, + ccUserUnBlocked: (payload: { user: CometChat.User }) => { + if (payload.user.getUid() === localUser.getUid()) { + setLocalUser(payload.user); + } + }, + }); + + return () => { + CometChatUIEventHandler.removeUserListener(listenerId); + }; + }, [localUser]); + + const handleUnblock = async () => { + try { + await CometChat.unblockUsers([localUser.getUid()]); + const freshUser = await CometChat.getUser(localUser.getUid()); + setLocalUser(freshUser); + + CometChatUIEventHandler.emitUserEvent( + CometChatUIEvents.ccUserUnBlocked, + { user: freshUser } + ); + } catch (error) { + console.error('Error unblocking user:', error); + } + }; + + if (localUser.getBlockedByMe()) { + return ( + + + {t('BLOCKED_USER_DESC')} + + + + {t('UNBLOCK')} + + + + ); + } + + return ; +}; +``` + +--- + +### 4. Block Option in User Info + +Add a block/unblock option in the user info or details screen. + +```tsx +import React, { useState } from 'react'; +import { View, TouchableOpacity, Text, Alert } from 'react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatUIEventHandler, + CometChatUIEvents, + useTheme, + useCometChatTranslation, +} from '@cometchat/chat-uikit-react-native'; + +interface UserInfoActionsProps { + user: CometChat.User; +} + +const UserInfoActions: React.FC = ({ user }) => { + const theme = useTheme(); + const { t } = useCometChatTranslation(); + const [localUser, setLocalUser] = useState(user); + + const handleBlockToggle = () => { + if (localUser.getBlockedByMe()) { + // Unblock directly + unblockUser(); + } else { + // Show confirmation before blocking + Alert.alert( + t('BLOCK_USER'), + t('BLOCK_USER_CONFIRMATION'), + [ + { text: t('CANCEL'), style: 'cancel' }, + { text: t('BLOCK'), style: 'destructive', onPress: blockUser }, + ] + ); + } + }; + + const blockUser = async () => { + try { + await CometChat.blockUsers([localUser.getUid()]); + const freshUser = await CometChat.getUser(localUser.getUid()); + setLocalUser(freshUser); + + CometChatUIEventHandler.emitUserEvent( + CometChatUIEvents.ccUserBlocked, + { user: freshUser } + ); + } catch (error) { + console.error('Error blocking user:', error); + } + }; + + const unblockUser = async () => { + try { + await CometChat.unblockUsers([localUser.getUid()]); + const freshUser = await CometChat.getUser(localUser.getUid()); + setLocalUser(freshUser); + + CometChatUIEventHandler.emitUserEvent( + CometChatUIEvents.ccUserUnBlocked, + { user: freshUser } + ); + } catch (error) { + console.error('Error unblocking user:', error); + } + }; + + return ( + + + {localUser.getBlockedByMe() ? t('UNBLOCK_USER') : t('BLOCK_USER')} + + + ); +}; +``` + +--- + +## Feature Matrix + +| Feature | Component / Method | +|:---|:---| +| Block user | `CometChat.blockUsers([UID])` | +| Unblock user | `CometChat.unblockUsers([UID])` | +| Check blocked status | `user.getBlockedByMe()` | +| Block event | `CometChatUIEvents.ccUserBlocked` | +| Unblock event | `CometChatUIEvents.ccUserUnBlocked` | +| Event listener | `CometChatUIEventHandler.addUserListener()` | + +--- + +## Next Steps + + + + Display and manage user lists. + + + Customize the message input component. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react-native/guide-group-chat.mdx b/ui-kit/react-native/guide-group-chat.mdx new file mode 100644 index 000000000..b92c30c38 --- /dev/null +++ b/ui-kit/react-native/guide-group-chat.mdx @@ -0,0 +1,408 @@ +--- +title: "Group Chat" +sidebarTitle: "Group Chat" +description: "Implement group management including create, join, members, roles, and ownership transfer in CometChat React Native UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key components | `CometChatGroups`, `CometChatGroupMembers`, `CometChatUsers`, `CometChatConfirmDialog` | +| Init | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Features | Create public/private/password-protected groups, manage members, roles, ownership transfer | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleApp) | +| Related | [Groups](/ui-kit/react-native/groups) · [Group Members](/ui-kit/react-native/group-members) · [All Guides](/ui-kit/react-native/guide-overview) | + + + +This guide covers the full group lifecycle: creating groups, joining them, managing members, changing roles, and transferring ownership. + +Before starting, complete the [Getting Started](/ui-kit/react-native/react-native-cli-integration) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChatGroups` | Displays list of groups with join/create options | +| `CometChatGroupMembers` | Displays and manages group member lists | +| `CometChatUsers` | User selection for adding members | +| `CometChatConfirmDialog` | Confirmation dialogs for destructive actions | +| `CometChatGroupsEvents` | Events for group-related actions | + +--- + +## Integration Steps + +### 1. Display Groups List + +Render `CometChatGroups` with custom app bar options for creating new groups. Handle item press to either open chat (if joined) or trigger join flow. + +```tsx +import React, { useState } from 'react'; +import { View, TouchableOpacity } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import { + CometChatGroups, + CometChatUIEventHandler, + CometChatUIEvents, + CometChatUIKit, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +const GroupsScreen = () => { + const navigation = useNavigation(); + const [isCreateGroupVisible, setCreateGroupVisible] = useState(false); + + const handleGroupItemPress = (group: CometChat.Group) => { + if (group.getHasJoined()) { + // Navigate to messages + navigation.navigate('Messages', { group }); + return; + } + + if (group.getType() === CometChat.GROUP_TYPE.PUBLIC) { + joinPublicGroup(group); + } else if (group.getType() === CometChat.GROUP_TYPE.PASSWORD) { + // Show password input modal + setGroupToJoin(group); + setJoinGroupVisible(true); + } + }; + + const joinPublicGroup = async (group: CometChat.Group) => { + try { + const joinedGroup = await CometChat.joinGroup( + group.getGuid(), + group.getType() as CometChat.GroupType, + '' + ); + + navigation.navigate('Messages', { group: joinedGroup }); + + CometChatUIEventHandler.emitGroupEvent( + CometChatUIEvents.ccGroupMemberJoined, + { + joinedUser: CometChatUIKit.loggedInUser, + joinedGroup: joinedGroup, + } + ); + } catch (error) { + console.log('Error joining public group:', error); + } + }; + + return ( + + ( + setCreateGroupVisible(true)}> + {/* Add icon */} + + )} + /> + + ); +}; +``` + +--- + +### 2. Create Group + +Build a form that collects group name, type, and optional password. Call `CometChat.createGroup()` and emit `ccGroupCreated`. + +```tsx +import React, { useState } from 'react'; +import { View, TextInput, TouchableOpacity, Text } from 'react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatUIEventHandler, + CometChatGroupsEvents, +} from '@cometchat/chat-uikit-react-native'; + +interface CreateGroupProps { + onGroupCreated: (group: CometChat.Group) => void; + onClose: () => void; +} + +const CreateGroupForm: React.FC = ({ onGroupCreated, onClose }) => { + const [groupName, setGroupName] = useState(''); + const [groupType, setGroupType] = useState(CometChat.GROUP_TYPE.PUBLIC); + const [password, setPassword] = useState(''); + + const handleCreateGroup = async () => { + const GUID = `group_${new Date().getTime()}`; + const group = new CometChat.Group(GUID, groupName, groupType, password); + + try { + const createdGroup = await CometChat.createGroup(group); + + CometChatUIEventHandler.emitGroupEvent( + CometChatGroupsEvents.ccGroupCreated, + { group: createdGroup } + ); + + onGroupCreated(createdGroup); + onClose(); + } catch (error) { + console.error('Group creation failed:', error); + } + }; + + return ( + + + + {/* Group type selector */} + + setGroupType(CometChat.GROUP_TYPE.PUBLIC)}> + Public + + setGroupType(CometChat.GROUP_TYPE.PRIVATE)}> + Private + + setGroupType(CometChat.GROUP_TYPE.PASSWORD)}> + Password + + + + {groupType === CometChat.GROUP_TYPE.PASSWORD && ( + + )} + + + Create Group + + + ); +}; +``` + +--- + +### 3. Add Members to Group + +Use `CometChatUsers` with `selectionMode="multiple"` to select users, then call `CometChat.addMembersToGroup()`. + +```tsx +import React, { useState, useCallback } from 'react'; +import { View, TouchableOpacity, Text } from 'react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatUsers, + CometChatUIEventHandler, + CometChatGroupsEvents, + CometChatUIKit, + CometChatUiKitConstants, +} from '@cometchat/chat-uikit-react-native'; + +interface AddMemberProps { + group: CometChat.Group; + onBack: () => void; +} + +const AddMemberScreen: React.FC = ({ group, onBack }) => { + const [selectedUsers, setSelectedUsers] = useState([]); + + const addMembersToGroup = useCallback(async () => { + try { + const membersList = selectedUsers.map((user) => { + const groupMember = new CometChat.GroupMember( + user.getUid(), + CometChat.GROUP_MEMBER_SCOPE.PARTICIPANT + ); + groupMember.setName(user.getName()); + return groupMember; + }); + + const guid = group.getGuid(); + const response = await CometChat.addMembersToGroup(guid, membersList, []); + + const addedUIDs = Object.entries(response) + .filter(([_, status]) => status === 'success') + .map(([uid]) => uid); + + if (addedUIDs.length > 0) { + // Emit event for each added member + membersList + .filter((member) => addedUIDs.includes(member.getUid())) + .forEach((member) => { + CometChatUIEventHandler.emitGroupEvent( + CometChatGroupsEvents.ccGroupMemberAdded, + { + addedBy: CometChatUIKit.loggedInUser, + usersAdded: [member], + userAddedIn: group, + } + ); + }); + + onBack(); + } + } catch (error) { + console.error('Failed to add members:', error); + } + }, [group, selectedUsers, onBack]); + + return ( + + + + + Add Members + + + ); +}; +``` + +--- + +### 4. View and Manage Group Members + +Use `CometChatGroupMembers` to display members with options for scope changes and removal. + +```tsx +import React from 'react'; +import { View } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import { CometChatGroupMembers } from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +interface ViewMembersProps { + group: CometChat.Group; +} + +const ViewMembersScreen: React.FC = ({ group }) => { + const navigation = useNavigation(); + + const handleMemberPress = (member: CometChat.GroupMember) => { + // Navigate to member profile or show options + console.log('Member pressed:', member.getName()); + }; + + return ( + + navigation.goBack()} + /> + + ); +}; +``` + +--- + +### 5. Transfer Ownership + +Let the current owner select a member and transfer ownership via `CometChat.transferGroupOwnership()`. + +```tsx +import React, { useState } from 'react'; +import { View, TouchableOpacity, Text } from 'react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatGroupMembers, + CometChatUIEventHandler, + CometChatGroupsEvents, +} from '@cometchat/chat-uikit-react-native'; + +interface TransferOwnershipProps { + group: CometChat.Group; + onClose: () => void; +} + +const TransferOwnershipScreen: React.FC = ({ group, onClose }) => { + const [selectedMember, setSelectedMember] = useState(null); + + const transferOwnership = async () => { + if (!selectedMember) return; + + try { + await CometChat.transferGroupOwnership(group.getGuid(), selectedMember.getUid()); + + CometChatUIEventHandler.emitGroupEvent( + CometChatGroupsEvents.ccOwnershipChanged, + { + group: group, + newOwner: selectedMember, + } + ); + + onClose(); + } catch (error) { + console.error('Ownership transfer failed:', error); + } + }; + + return ( + + setSelectedMember(members[0] || null)} + /> + + + Transfer Ownership + + + ); +}; +``` + +--- + +## Feature Matrix + +| Feature | Component / Method | +|:---|:---| +| Display groups | `CometChatGroups` | +| Create group | `CometChat.createGroup()` | +| Join group | `CometChat.joinGroup()` | +| View members | `CometChatGroupMembers` | +| Add members | `CometChat.addMembersToGroup()` | +| Remove member | `CometChat.kickGroupMember()` | +| Ban member | `CometChat.banGroupMember()` | +| Change scope | `CometChat.updateGroupMemberScope()` | +| Transfer ownership | `CometChat.transferGroupOwnership()` | +| Group events | `CometChatGroupsEvents` | + +--- + +## Next Steps + + + + Display and manage group lists. + + + Display and manage group member lists. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react-native/guide-new-chat.mdx b/ui-kit/react-native/guide-new-chat.mdx new file mode 100644 index 000000000..3614742b3 --- /dev/null +++ b/ui-kit/react-native/guide-new-chat.mdx @@ -0,0 +1,348 @@ +--- +title: "New Chat" +sidebarTitle: "New Chat" +description: "Build a unified new chat entry point for starting 1:1 or group conversations in CometChat React Native UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key components | `CometChatUsers`, `CometChatGroups`, `CometChatConversations` | +| Init | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Unified new chat entry point for starting 1:1 or group conversations | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleApp) | +| Related | [Users](/ui-kit/react-native/users) · [Groups](/ui-kit/react-native/groups) · [All Guides](/ui-kit/react-native/guide-overview) | + + + +The New Chat feature lets users start conversations with other users or join group conversations from a single interface. + +Before starting, complete the [Getting Started](/ui-kit/react-native/react-native-cli-integration) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChatUsers` | Displays list of available users for chat creation | +| `CometChatGroups` | Shows available groups for joining | +| `CometChatConversations` | Main conversations list | + +--- + +## Integration Steps + + +### 1. New Chat Screen with Tabs + +Create a screen with tabs to switch between Users and Groups lists. + +```tsx +import React, { useState } from 'react'; +import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import { + CometChatUsers, + CometChatGroups, + useTheme, + useCometChatTranslation, + Icon, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +const NewChatScreen = () => { + const navigation = useNavigation(); + const theme = useTheme(); + const { t } = useCometChatTranslation(); + const [selectedTab, setSelectedTab] = useState<'user' | 'group'>('user'); + + const handleUserPress = (user: CometChat.User) => { + navigation.navigate('Messages', { user }); + }; + + const handleGroupPress = (group: CometChat.Group) => { + if (group.getHasJoined()) { + navigation.navigate('Messages', { group }); + } else { + // Handle join flow for non-joined groups + handleJoinGroup(group); + } + }; + + const handleJoinGroup = async (group: CometChat.Group) => { + if (group.getType() === CometChat.GROUP_TYPE.PUBLIC) { + try { + const joinedGroup = await CometChat.joinGroup( + group.getGuid(), + group.getType() as CometChat.GroupType, + '' + ); + navigation.navigate('Messages', { group: joinedGroup }); + } catch (error) { + console.error('Error joining group:', error); + } + } else if (group.getType() === CometChat.GROUP_TYPE.PASSWORD) { + // Show password input modal + navigation.navigate('JoinGroup', { group }); + } + }; + + return ( + + {/* Header */} + + navigation.goBack()}> + {/* Back icon */} + + + {t('NEW_CHAT')} + + + + {/* Tabs */} + + setSelectedTab('user')} + > + + {t('USERS')} + + + setSelectedTab('group')} + > + + {t('GROUPS')} + + + + + {/* Content */} + + {selectedTab === 'user' ? ( + + ) : ( + + )} + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, + header: { + flexDirection: 'row', + alignItems: 'center', + padding: 15, + borderBottomWidth: 1, + }, + tabs: { + flexDirection: 'row', + }, + tab: { + flex: 1, + paddingVertical: 15, + alignItems: 'center', + }, +}); + +export default NewChatScreen; +``` + +--- + +### 2. Add New Chat Button to Conversations + +Add a floating action button or header option to launch the new chat screen. + +```tsx +import React from 'react'; +import { View, TouchableOpacity, StyleSheet } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import { + CometChatConversations, + useTheme, + Icon, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +const ConversationsScreen = () => { + const navigation = useNavigation(); + const theme = useTheme(); + + const handleConversationPress = (conversation: CometChat.Conversation) => { + const conversationWith = conversation.getConversationWith(); + + if (conversationWith instanceof CometChat.User) { + navigation.navigate('Messages', { user: conversationWith }); + } else if (conversationWith instanceof CometChat.Group) { + navigation.navigate('Messages', { group: conversationWith }); + } + }; + + const handleNewChatPress = () => { + navigation.navigate('NewChat'); + }; + + return ( + + ( + + {/* New chat icon */} + + )} + /> + + {/* Floating Action Button */} + + {/* Plus icon */} + + + ); +}; + +const styles = StyleSheet.create({ + fab: { + position: 'absolute', + bottom: 20, + right: 20, + width: 56, + height: 56, + borderRadius: 28, + justifyContent: 'center', + alignItems: 'center', + elevation: 4, + shadowColor: '#000', + shadowOffset: { width: 0, height: 2 }, + shadowOpacity: 0.25, + shadowRadius: 4, + }, +}); + +export default ConversationsScreen; +``` + +--- + +### 3. Create Conversation Screen + +A dedicated screen for creating new 1:1 conversations by selecting a user. + +```tsx +import React from 'react'; +import { View } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import { + CometChatUsers, + useTheme, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +const CreateConversationScreen = () => { + const navigation = useNavigation(); + const theme = useTheme(); + + const handleUserSelect = (user: CometChat.User) => { + // Navigate directly to messages with selected user + navigation.replace('Messages', { user }); + }; + + return ( + + navigation.goBack()} + /> + + ); +}; + +export default CreateConversationScreen; +``` + +--- + +### 4. Navigation Setup + +Configure navigation to include all new chat related screens. + +```tsx +import { createNativeStackNavigator } from '@react-navigation/native-stack'; +import ConversationsScreen from './screens/ConversationsScreen'; +import NewChatScreen from './screens/NewChatScreen'; +import CreateConversationScreen from './screens/CreateConversationScreen'; +import MessagesScreen from './screens/MessagesScreen'; + +const Stack = createNativeStackNavigator(); + +const AppNavigator = () => { + return ( + + + + + + + ); +}; +``` + +--- + +## Feature Matrix + +| Feature | Component / Method | +|:---|:---| +| User selection | `CometChatUsers` with `onItemPress` | +| Group selection | `CometChatGroups` with `onItemPress` | +| Join public group | `CometChat.joinGroup()` | +| Navigate to chat | `navigation.navigate('Messages', { user/group })` | +| Tab navigation | Custom tabs with state management | + +--- + +## Next Steps + + + + Display and manage conversation lists. + + + Display and manage user lists. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react-native/guide-overview.mdx b/ui-kit/react-native/guide-overview.mdx new file mode 100644 index 000000000..7222c4ac4 --- /dev/null +++ b/ui-kit/react-native/guide-overview.mdx @@ -0,0 +1,60 @@ +--- +title: "Overview" +sidebarTitle: "Overview" +description: "Index of task-oriented feature guides for the CometChat React Native UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Purpose | Index of task-oriented feature guides for the React Native UI Kit | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleApp) | +| Components | [Components Overview](/ui-kit/react-native/components-overview) | +| Guides | [AI Agent](/ui-kit/react-native/guide-ai-agent) · [New Chat](/ui-kit/react-native/guide-new-chat) · [Group Chat](/ui-kit/react-native/guide-group-chat) · [Threaded Messages](/ui-kit/react-native/guide-threaded-messages) · [Search Messages](/ui-kit/react-native/guide-search-messages) · [Block/Unblock](/ui-kit/react-native/guide-block-unblock-user) | + + + +> This page indexes focused, task‑oriented feature guides for the React Native UI Kit. Each guide shows how to implement a specific capability end‑to‑end using UI components. + +## When to Use These Guides + +Use these guides after completing the base [Getting Started](/ui-kit/react-native/react-native-cli-integration) (or [Expo Integration](/ui-kit/react-native/expo-integration)). They help you layer additional UX without rewriting core chat flows. + +## Guide Directory + +| Guide | Description | +|:------|:------------| +| [AI Agent Integration](/ui-kit/react-native/guide-ai-agent) | Enable intelligent conversational AI capabilities with AI Agent integration, chat history, and contextual responses. | +| [New Chat](/ui-kit/react-native/guide-new-chat) | Unified entry for starting new 1:1 or group chats with user & group discovery. | +| [Group Management](/ui-kit/react-native/guide-group-chat) | Create/join groups, view members, add/ban users, change roles/scopes, transfer ownership. | +| [Threaded Messages](/ui-kit/react-native/guide-threaded-messages) | Threaded replies: open parent context, list replies, compose within focused thread. | +| [Search Messages](/ui-kit/react-native/guide-search-messages) | Add full‑text message search across conversations with result routing into context. | +| [Block/Unblock User](/ui-kit/react-native/guide-block-unblock-user) | Let users block or unblock others in 1:1 chats; hides composer and shows an unblock prompt. | +| [Custom Text Formatter](/ui-kit/react-native/custom-text-formatter-guide) | Extend the base formatter to implement custom inline patterns (hashtags, keywords) with regex + callbacks. | +| [Mentions Formatter](/ui-kit/react-native/mentions-formatter-guide) | Add @mentions with styled tokens, suggestion list, and click handling for users & members. | +| [URL Formatter](/ui-kit/react-native/url-formatter-guide) | Detect and style plain URLs, emails, and phone numbers as clickable links. | +| [Shortcut Formatter](/ui-kit/react-native/shortcut-formatter-guide) | Provide !shortcut style expansions invoking extension APIs before inserting content. | +| [Apple Privacy Manifest](/ui-kit/react-native/apple-privacy-manifest-guide) | Configure required Apple Privacy Manifest for App Store compliance. | + +Need another guide? Open a request via our [Support Portal](https://help.cometchat.com/hc/en-us/requests/new). + +--- + +## Next Steps + + + + Set up the React Native UI Kit + + + Explore all UI components + + + Customize themes and styling + + + Handle UI Kit events + + diff --git a/ui-kit/react-native/guide-search-messages.mdx b/ui-kit/react-native/guide-search-messages.mdx new file mode 100644 index 000000000..eae7b90bb --- /dev/null +++ b/ui-kit/react-native/guide-search-messages.mdx @@ -0,0 +1,310 @@ +--- +title: "Search Messages" +sidebarTitle: "Search Messages" +description: "Add full-text message search across conversations with result routing in CometChat React Native UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key components | `CometChatSearch`, `CometChatMessageList` | +| Init | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Full-text message search across conversations with result routing and navigation | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleApp) | +| Related | [Message List](/ui-kit/react-native/message-list) · [All Guides](/ui-kit/react-native/guide-overview) | + + + +Search Messages lets users locate specific messages across conversations and groups using keyword search, then navigate directly to the result. + +Before starting, complete the [Getting Started](/ui-kit/react-native/react-native-cli-integration) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChatSearch` | Main search interface with conversation and message results | +| `CometChatMessageList` | Displays messages with search highlighting via `searchKeyword` prop | + +--- + +## Integration Steps + +### 1. Search Messages Screen + +Create a dedicated search screen using `CometChatSearch` component. + +```tsx +import React, { useCallback } from 'react'; +import { View, StyleSheet, BackHandler, Platform } from 'react-native'; +import { useRoute, useNavigation } from '@react-navigation/native'; +import { + CometChatSearch, + useTheme, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +const SearchMessagesScreen = () => { + const route = useRoute(); + const navigation = useNavigation(); + const theme = useTheme(); + const { user, group } = route.params || {}; + + // Handle back button + const handleBack = useCallback(() => { + navigation.goBack(); + }, [navigation]); + + // Handle conversation click from search results + const handleConversationClicked = useCallback( + (conversation: CometChat.Conversation, searchKeyword?: string) => { + const conversationWith = conversation.getConversationWith(); + + if (conversationWith instanceof CometChat.User) { + navigation.navigate('Messages', { + user: conversationWith, + searchKeyword, + }); + } else if (conversationWith instanceof CometChat.Group) { + navigation.navigate('Messages', { + group: conversationWith, + searchKeyword, + }); + } + }, + [navigation] + ); + + // Handle message click from search results + const handleMessageClicked = useCallback( + async (message: CometChat.BaseMessage, searchKeyword?: string) => { + const messageReceiver = message.getReceiver(); + const parentMessageId = message.getParentMessageId(); + + let targetUser: CometChat.User | undefined; + let targetGroup: CometChat.Group | undefined; + + if (messageReceiver instanceof CometChat.User) { + const sender = message.getSender(); + const loggedInUser = await CometChat.getLoggedinUser(); + + if (sender.getUid() === loggedInUser?.getUid()) { + targetUser = messageReceiver; + } else { + targetUser = sender; + } + } else if (messageReceiver instanceof CometChat.Group) { + targetGroup = messageReceiver; + } + + // If message is in a thread, navigate to thread view + if (parentMessageId) { + try { + const parentMessage = await CometChat.getMessageDetails(parentMessageId); + if (parentMessage) { + navigation.navigate('ThreadView', { + message: parentMessage, + user: targetUser, + group: targetGroup, + highlightMessageId: String(message.getId()), + }); + return; + } + } catch (e) { + console.error('Failed to fetch parent message', e); + } + } + + // Navigate to messages screen with highlight + if (targetUser) { + navigation.navigate('Messages', { + user: targetUser, + messageId: String(message.getId()), + searchKeyword, + }); + } else if (targetGroup) { + navigation.navigate('Messages', { + group: targetGroup, + messageId: String(message.getId()), + searchKeyword, + }); + } + }, + [navigation] + ); + + // Determine placeholder text + let searchPlaceholder = 'Search'; + if (user?.getName()) { + searchPlaceholder = `Search in ${user.getName()}`; + } else if (group?.getName()) { + searchPlaceholder = `Search in ${group.getName()}`; + } + + return ( + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, +}); + +export default SearchMessagesScreen; +``` + +--- + +### 2. Trigger Search from Messages Screen + +Add a search button to your messages header that navigates to the search screen. + +```tsx +import React from 'react'; +import { View, TouchableOpacity } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + Icon, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +interface MessagesScreenProps { + user?: CometChat.User; + group?: CometChat.Group; + messageId?: string; + searchKeyword?: string; +} + +const MessagesScreen: React.FC = ({ + user, + group, + messageId, + searchKeyword, +}) => { + const navigation = useNavigation(); + + const handleSearchPress = () => { + navigation.navigate('SearchMessages', { user, group }); + }; + + return ( + + ( + + {/* Search icon */} + + )} + /> + + + + + + ); +}; +``` + +--- + +### 3. Highlight Search Results + +When navigating from search results, pass `searchKeyword` to highlight matching text in messages. + +```tsx + +``` + +--- + +### 4. Navigation Setup + +Add the search screen to your navigation stack. + +```tsx +import { createNativeStackNavigator } from '@react-navigation/native-stack'; +import MessagesScreen from './screens/MessagesScreen'; +import SearchMessagesScreen from './screens/SearchMessagesScreen'; +import ThreadView from './screens/ThreadView'; + +const Stack = createNativeStackNavigator(); + +const AppNavigator = () => { + return ( + + + + + + ); +}; +``` + +--- + +## Feature Matrix + +| Feature | Component / Prop | +|:---|:---| +| Search interface | `CometChatSearch` | +| Conversation results | `onConversationClicked` callback | +| Message results | `onMessageClicked` callback | +| Scoped search | `uid` or `guid` props to limit search scope | +| Keyword highlighting | `searchKeyword` prop on `CometChatMessageList` | +| Navigate to message | `goToMessageId` prop on `CometChatMessageList` | + +--- + +## Next Steps + + + + Render real-time message threads. + + + Implement threaded message replies. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react-native/guide-threaded-messages.mdx b/ui-kit/react-native/guide-threaded-messages.mdx new file mode 100644 index 000000000..75febe45c --- /dev/null +++ b/ui-kit/react-native/guide-threaded-messages.mdx @@ -0,0 +1,310 @@ +--- +title: "Threaded Messages" +sidebarTitle: "Threaded Messages" +description: "Implement threaded message replies with parent context, reply list, and focused thread composer in CometChat React Native UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key components | `CometChatThreadHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Init | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Entry point | Pass `parentMessageId` prop to `CometChatMessageList` and `CometChatMessageComposer` | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleApp) | +| Related | [Message List](/ui-kit/react-native/message-list) · [Thread Header](/ui-kit/react-native/threaded-messages-header) · [All Guides](/ui-kit/react-native/guide-overview) | + + + +Threaded messages let users create sub-conversations by replying to specific messages in group chats. This reduces clutter and keeps discussions focused. + +Before starting, complete the [Getting Started](/ui-kit/react-native/react-native-cli-integration) guide. + +--- + +## Components + +| Component / Class | Role | +|:---|:---| +| `CometChatThreadHeader` | Displays parent message context | +| `CometChatMessageList` | Shows messages filtered by `parentMessageId` | +| `CometChatMessageComposer` | Input for composing threaded replies | + +--- + +## Integration Steps + +### 1. Thread View Screen + +Create a dedicated screen for threaded messages that receives the parent message via navigation params. + +```tsx +import React, { useCallback } from 'react'; +import { View, Text, TouchableOpacity, StyleSheet } from 'react-native'; +import { useRoute, useNavigation } from '@react-navigation/native'; +import { + CometChatThreadHeader, + CometChatMessageList, + CometChatMessageComposer, + useTheme, + useCometChatTranslation, + Icon, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +const ThreadView = () => { + const route = useRoute(); + const navigation = useNavigation(); + const theme = useTheme(); + const { t } = useCometChatTranslation(); + + const { message, user, group } = route.params || {}; + + const handleBack = useCallback(() => { + navigation.goBack(); + }, [navigation]); + + return ( + + {/* Custom Header */} + + + {/* Back icon */} + + + + {t('THREAD')} + + + {user ? user.getName() : group?.getName()} + + + + + {/* Thread Header - shows parent message */} + + + {/* Threaded Message List */} + + + + + {/* Message Composer for Thread */} + + + ); +}; + +const styles = StyleSheet.create({ + headerStyle: { + paddingVertical: 10, + paddingLeft: 10, + flexDirection: 'row', + }, + textStyle: { + paddingLeft: 10, + alignItems: 'flex-start', + }, +}); + +export default ThreadView; +``` + +--- + +### 2. Trigger Thread View from Messages + +In your main messages screen, handle the `onThreadRepliesClick` callback to navigate to the thread view. + +```tsx +import React from 'react'; +import { View } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from '@cometchat/chat-uikit-react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; + +interface MessagesScreenProps { + user?: CometChat.User; + group?: CometChat.Group; +} + +const MessagesScreen: React.FC = ({ user, group }) => { + const navigation = useNavigation(); + + const handleThreadRepliesClick = (message: CometChat.BaseMessage) => { + navigation.navigate('ThreadView', { + message, + user, + group, + }); + }; + + return ( + + + + + + + + ); +}; +``` + +--- + +### 3. Navigation Setup + +Configure React Navigation to include the ThreadView screen. + +```tsx +import { createNativeStackNavigator } from '@react-navigation/native-stack'; +import MessagesScreen from './screens/MessagesScreen'; +import ThreadView from './screens/ThreadView'; + +const Stack = createNativeStackNavigator(); + +const AppNavigator = () => { + return ( + + + + + ); +}; +``` + +--- + +### 4. Navigate to Specific Message in Thread + +Support navigating to a specific message within a thread using `goToMessageId` prop. + +```tsx + +``` + +--- + +### 5. Handle Blocked Users in Threads + +Show an unblock prompt when the user is blocked instead of the composer. + +```tsx +import React, { useState } from 'react'; +import { View, Text, TouchableOpacity } from 'react-native'; +import { CometChat } from '@cometchat/chat-sdk-react-native'; +import { + CometChatMessageComposer, + CometChatUIEventHandler, + CometChatUIEvents, + useTheme, + useCometChatTranslation, +} from '@cometchat/chat-uikit-react-native'; + +interface ThreadComposerProps { + user?: CometChat.User; + group?: CometChat.Group; + parentMessageId: number; +} + +const ThreadComposer: React.FC = ({ user, group, parentMessageId }) => { + const theme = useTheme(); + const { t } = useCometChatTranslation(); + const [localUser, setLocalUser] = useState(user); + + const unblock = async () => { + if (!localUser) return; + + try { + await CometChat.unblockUsers([localUser.getUid()]); + const freshUser = await CometChat.getUser(localUser.getUid()); + setLocalUser(freshUser); + + CometChatUIEventHandler.emitUserEvent( + CometChatUIEvents.ccUserUnBlocked, + { user: freshUser } + ); + } catch (error) { + console.error('Error unblocking user:', error); + } + }; + + if (localUser?.getBlockedByMe()) { + return ( + + + {t('BLOCKED_USER_DESC')} + + + {t('UNBLOCK')} + + + ); + } + + return ( + + ); +}; +``` + +--- + +## Feature Matrix + +| Feature | Component / Prop | +|:---|:---| +| Display parent message | `CometChatThreadHeader` with `parentMessage` prop | +| Show thread replies | `CometChatMessageList` with `parentMessageId` prop | +| Compose thread reply | `CometChatMessageComposer` with `parentMessageId` prop | +| Navigate to message | `goToMessageId` prop on `CometChatMessageList` | +| Thread trigger | `onThreadRepliesClick` callback on `CometChatMessageList` | + +--- + +## Next Steps + + + + Render real-time message threads. + + + Customize the thread header component. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react-native/incoming-call.mdx b/ui-kit/react-native/incoming-call.mdx index 5bf8d4f3f..981851733 100644 --- a/ui-kit/react-native/incoming-call.mdx +++ b/ui-kit/react-native/incoming-call.mdx @@ -1,63 +1,97 @@ --- title: "Incoming Call" +description: "Display and handle incoming voice and video calls with CometChatIncomingCall component in React Native UI Kit, providing options to accept or decline." --- -## Overview + +```json +{ + "component": "CometChatIncomingCall", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatIncomingCall } from \"@cometchat/chat-uikit-react-native\";", + "description": "Visual representation for incoming voice and video calls with accept/decline options.", + "props": { + "data": { + "call": { + "type": "CometChat.Call | CometChat.CustomMessage", + "note": "The incoming call object" + } + }, + "callbacks": { + "onAccept": "(call: CometChat.BaseMessage) => void", + "onDecline": "(call: CometChat.BaseMessage) => void", + "onError": "(error: CometChat.CometChatException) => void" + }, + "sound": { + "disableSoundForCalls": { "type": "boolean", "default": false }, + "customSoundForCalls": { "type": "string", "default": "built-in" } + }, + "viewSlots": { + "ItemView": "(call) => JSX.Element", + "LeadingView": "(call) => JSX.Element", + "TitleView": "(call) => JSX.Element", + "SubtitleView": "(call) => JSX.Element", + "TrailingView": "(call) => JSX.Element" + } + }, + "events": [ + { "name": "ccCallRejected", "payload": "{ call }", "description": "Call rejected by receiver" }, + { "name": "ccCallAccepted", "payload": "{ call }", "description": "Call accepted by receiver" }, + { "name": "ccCallEnded", "payload": "{ call }", "description": "Call successfully ended" }, + { "name": "ccCallFailled", "payload": "{ call }", "description": "Error during call" } + ] +} +``` + + +## Where It Fits -The `CometChatIncomingCall` is a [Component](/ui-kit/react-native/components-overview#components) that serves as a visual representation when the user receives an incoming call, such as a voice call or video call, providing options to answer or decline the call. +`CometChatIncomingCall` is a [Component](/ui-kit/react-native/components-overview#components) that serves as a visual representation when the user receives an incoming call, such as a voice call or video call, providing options to answer or decline the call. -*** - -## Usage - -### Integration +--- -`CometChatIncomingCall` being a custom component, offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. +## Minimal Render - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; +import { useState, useRef, useEffect } from "react"; -function App(): React.JSX.Element { - const incomingCall = useRef(null); +function IncomingCallDemo() { + const incomingCall = useRef(null); const [callReceived, setCallReceived] = useState(false); - const listnerID = "UNIQUE_LISTENER_ID"; + const listenerId = "INCOMING_CALL_LISTENER"; useEffect(() => { - //code CometChat.addCallListener( - listnerID, + listenerId, new CometChat.CallListener({ onIncomingCallReceived: (call) => { incomingCall.current = call; setCallReceived(true); }, - onOutgoingCallRejected: (call) => { - incomingCall.current = null; - setCallReceived(false); - }, onIncomingCallCancelled: (call) => { incomingCall.current = null; setCallReceived(false); }, }) ); - }); + + return () => { + CometChat.removeCallListener(listenerId); + }; + }, []); return ( <> - {callReceived && ( + {callReceived && incomingCall.current && ( { - setCallReceived(false); - }} + call={incomingCall.current} + onDecline={() => setCallReceived(false)} /> )} @@ -65,494 +99,313 @@ function App(): React.JSX.Element { } ``` - - - +--- -*** +## Actions and Events -### Actions +### Callback Props -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +#### onAccept -##### onAccept +Fires when the accept button is pressed. -`onAccept` is triggered when you click the accept button of the `Incoming Call` component. You can override this action using the following code snippet. +```tsx lines +onAccept?: (call: CometChat.BaseMessage) => void +``` - - -```tsx -import { CometChat } from "@cometchat/chat-sdk-react-native"; +```tsx lines import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -function App(): React.JSX.Element { - const incomingCall = useRef(null); - const [callReceived, setCallReceived] = useState(false); - const listnerID = "UNIQUE_LISTENER_ID"; - - useEffect(() => { - //code - CometChat.addCallListener( - listnerID, - new CometChat.CallListener({ - onIncomingCallReceived: (call) => { - incomingCall.current = call; - setCallReceived(true); - }, - onOutgoingCallRejected: (call) => { - incomingCall.current = null; - setCallReceived(false); - }, - onIncomingCallCancelled: (call) => { - incomingCall.current = null; - setCallReceived(false); - }, - }) - ); - }); - - const onAcceptHandler = (message: CometChat.BaseMessage) => { - //code +function IncomingCallWithAccept() { + const handleAccept = (call: CometChat.BaseMessage) => { + console.log("Call accepted:", call); }; return ( - <> - {callReceived && ( - { - setCallReceived(false); - }} - onAccept={onAcceptHandler} - /> - )} - + setCallReceived(false)} + /> ); } ``` - +#### onDecline - +Fires when the decline button is pressed. -##### onDecline - -`onDecline` is triggered when you click the Decline button of the `Incoming Call` component. This action does not have a predefined behavior. You can override this action using the following code snippet. +```tsx lines +onDecline?: (call: CometChat.BaseMessage) => void +``` - - -```tsx -import { CometChat } from "@cometchat/chat-sdk-react-native"; +```tsx lines import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; -function App(): React.JSX.Element { - const incomingCall = useRef(null); - const [callReceived, setCallReceived] = useState(false); - const listnerID = "UNIQUE_LISTENER_ID"; - - useEffect(() => { - //code - CometChat.addCallListener( - listnerID, - new CometChat.CallListener({ - onIncomingCallReceived: (call) => { - incomingCall.current = call; - setCallReceived(true); - }, - onOutgoingCallRejected: (call) => { - incomingCall.current = null; - setCallReceived(false); - }, - onIncomingCallCancelled: (call) => { - incomingCall.current = null; - setCallReceived(false); - }, - }) - ); - }); - - const onDeclineHandler = (call) => { +function IncomingCallWithDecline() { + const handleDecline = (call) => { + console.log("Call declined"); setCallReceived(false); }; return ( - <> - {callReceived && ( - - )} - + ); } ``` - - - +#### onError -##### onError +Fires on internal errors (network failure, auth issue, SDK exception). -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Banned Members component. +```tsx lines +onError?: (error: CometChat.CometChatException) => void +``` - - -```tsx -import { CometChat } from "@cometchat/chat-sdk-react-native"; +```tsx lines import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -function App(): React.JSX.Element { - const incomingCall = useRef(null); - const [callReceived, setCallReceived] = useState(false); - const listnerID = "UNIQUE_LISTENER_ID"; - - useEffect(() => { - //code - CometChat.addCallListener( - listnerID, - new CometChat.CallListener({ - onIncomingCallReceived: (call) => { - incomingCall.current = call; - setCallReceived(true); - }, - onOutgoingCallRejected: (call) => { - incomingCall.current = null; - setCallReceived(false); - }, - onIncomingCallCancelled: (call) => { - incomingCall.current = null; - setCallReceived(false); - }, - }) - ); - }); - - const onErrorHandler = (error: CometChat.CometChatException) => { - //code - }; - +function IncomingCallWithError() { return ( - <> - {callReceived && ( - { - setCallReceived(false); - }} - onError={onErrorHandler} - /> - )} - + setCallReceived(false)} + onError={(error: CometChat.CometChatException) => { + console.error("IncomingCall error:", error); + }} + /> ); } ``` - - - +### Global UI Events -*** +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Add listeners and remove them on cleanup. -### Filters +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccCallRejected` | Initiated call is rejected by the receiver | `{ call }` | +| `ccCallAccepted` | Initiated call is accepted by the receiver | `{ call }` | +| `ccCallEnded` | Initiated call successfully ends | `{ call }` | +| `ccCallFailled` | Error occurs during the initiated call | `{ call }` | -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +When to use: sync external UI with call state changes. For example, update a call status indicator, show notifications, or log call events. -The IncomingCall component does not have any exposed filters. - -*** - -### Events - -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The list of events emitted by the Incoming Call component is as follows. - -| Event | Description | -| ------------------ | ---------------------------------------------------------------------------- | -| **ccCallRejected** | This event is triggered when the initiated call is rejected by the receiver. | -| **ccCallAccepted** | This event is triggered when the initiated call is accepted by the receiver. | -| **ccCallEnded** | This event is triggered when the initiated call successfully ends. | -| **ccCallFailled** | This event is triggered when an error occurs during the intiated call. | - - - -```tsx +```tsx lines +import { useEffect } from "react"; import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallRejected: ({ call }) => { - //code - }, -}); - -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallAccepted: ({ call }) => { - //code - }, -}); - -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallEnded: ({ call }) => { - //code - }, -}); - -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallFailled: ({ call }) => { - //code - }, -}); -``` - - - - - -*** - - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; - -CometChatUIEventHandler.removeCallListener("CALL_LISTENER_ID"); +function useIncomingCallEvents() { + useEffect(() => { + const listenerId = "INCOMING_CALL_EVENTS_" + Date.now(); + + CometChatUIEventHandler.addCallListener(listenerId, { + ccCallRejected: ({ call }) => { + console.log("Call rejected:", call); + }, + ccCallAccepted: ({ call }) => { + console.log("Call accepted:", call); + }, + ccCallEnded: ({ call }) => { + console.log("Call ended:", call); + }, + ccCallFailled: ({ call }) => { + console.log("Call failed:", call); + }, + }); + + return () => { + CometChatUIEventHandler.removeCallListener(listenerId); + }; + }, []); +} ``` - - - - -*** +--- -## Customization +## Custom View Slots -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +Each slot replaces a section of the default UI. Slots that accept a call parameter receive the call object for customization. -### Style +| Slot | Signature | Replaces | +| --- | --- | --- | +| `ItemView` | `(call) => JSX.Element` | Entire incoming call card | +| `LeadingView` | `(call) => JSX.Element` | Avatar / left section | +| `TitleView` | `(call) => JSX.Element` | Caller name / title text | +| `SubtitleView` | `(call) => JSX.Element` | Call type / status text | +| `TrailingView` | `(call) => JSX.Element` | Accept/decline buttons | -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +### ItemView -You can customize the appearance of the `IncomingCall` Component by applying the `IncomingCallStyle` to it using the following code snippet. +Custom view for the entire incoming call card. -```javascript -import { - CometChatIncomingCall, - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; -//code -return ( - - {callReceived && ( - { - setCallReceived(false); - }} - style={{ - containerStyle: { - backgroundColor: theme.color.extendedPrimary100, - }, - avatarStyle: { - containerStyle: { - backgroundColor: theme.color.extendedPrimary500, - borderRadius: 8, - }, - imageStyle: { - borderRadius: 8, - }, - }, - declineCallButtonStyle: { - backgroundColor: theme.color.staticWhite, - }, - declineCallTextStyle: { - color: theme.color.error, - }, - acceptCallButtonStyle: { - backgroundColor: theme.color.primary, - }, - }} - /> - )} - -); +```tsx lines +ItemView?: (call: CometChat.Call | CometChat.CustomMessage) => JSX.Element ``` - - - - -### Functionality - -In this example, we're enhancing the interface by customizing the accept and decline button icons. By setting custom icons for both the accept and decline buttons, users can enjoy a more visually appealing and personalized experience. - -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ------------------------ | --------------------------------------------------------------------------------- | -------------------------------- | -| **call** | CometChat call object consumed by the component to launch itself | `disableSoundForMessages={true}` | -| **customSoundForCalls** | Used to set custom sound for incoming calls | `customSoundForCalls?: string` | -| **disableSoundForCalls** | Used to disable/enable the sound of incoming calls, by default it is set to false | `disableSoundForCalls?: string` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -#### ItemView - -Allows setting a custom view for rendering each conversation item in the fetched list. - -Use Cases: - -* Customize the call card UI for incoming calls. -* Display additional user details (e.g., caller ID, location). -* Integrate custom animations for call alerts. - -```javascript +```tsx lines import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - - {callReceived && ( - { - setCallReceived(false); - }} - ItemView={(call: CometChat.Call | CometChat.CustomMessage) => { - //return JSX; - }} - /> - )} - -); -``` +import { View, Text } from "react-native"; + +function ItemViewDemo() { + const getItemView = (call: CometChat.Call | CometChat.CustomMessage) => { + return ( + + Incoming Call + + ); + }; -#### LeadingView + return ( + setCallReceived(false)} + ItemView={getItemView} + /> + ); +} +``` -Customizes the leading section of the component, usually the caller’s avatar or profile picture. +### LeadingView -Use Cases: +Custom view for the avatar / left section. -* Display a profile picture with call status effects. -* Show a custom ringing animation around the avatar. -* Replace the avatar with a caller ID card. +```tsx lines +LeadingView?: (call: CometChat.Call | CometChat.CustomMessage) => JSX.Element +``` -```javascript +```tsx lines import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - - {callReceived && ( - { - setCallReceived(false); - }} - LeadingView={(call: CometChat.Call | CometChat.CustomMessage) => { - //return JSX; - }} - /> - )} - -); -``` +import { View, Text } from "react-native"; + +function LeadingViewDemo() { + const getLeadingView = (call: CometChat.Call | CometChat.CustomMessage) => { + const caller = call.getCallInitiator(); + return ( + + + {caller.getName().charAt(0)} + + + ); + }; -#### TitleView + return ( + setCallReceived(false)} + LeadingView={getLeadingView} + /> + ); +} +``` -Allows setting a custom title view, typically used for the caller’s name or call type. +### SubtitleView -Use Cases: +Custom view for the call type / status text. -* Display the caller’s full name with a verified badge. -* Indicate the call type (Voice Call, Video Call). -* Show real-time status ("Ringing...", "Call from Work Contact", etc.). +```tsx lines +SubtitleView?: (call: CometChat.Call | CometChat.CustomMessage) => JSX.Element +``` -```javascript +```tsx lines import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - - {callReceived && ( - { - setCallReceived(false); - }} - TitleView={(call: CometChat.Call | CometChat.CustomMessage) => { - //return JSX; - }} - /> - )} - -); +import { Text } from "react-native"; + +function SubtitleViewDemo() { + const getSubtitleView = (call: CometChat.Call | CometChat.CustomMessage) => { + const callType = call.getType() === "audio" ? "Voice Call" : "Video Call"; + return {callType}; + }; + + return ( + setCallReceived(false)} + SubtitleView={getSubtitleView} + /> + ); +} ``` -#### SubtitleView +--- -Enables customizing the subtitle view, typically used for additional call details. +## Styling -Use Cases: +Using Style you can customize the look and feel of the component in your app. Pass a styling object as a prop to the `CometChatIncomingCall` component. -* Display call duration if available. -* Show network strength indicators. -* Include a custom message like "Connecting...". + + + -```javascript -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - - {callReceived && ( - { - setCallReceived(false); - }} - SubtitleView={(call: CometChat.Call | CometChat.CustomMessage) => { - //return JSX; - }} - /> - )} - -); -``` +```tsx lines +import { CometChatIncomingCall, useTheme } from "@cometchat/chat-uikit-react-native"; -#### TrailingView +function StylingDemo() { + const theme = useTheme(); -Customizes the trailing section for actions or additional call-related UI elements. + return ( + setCallReceived(false)} + style={{ + containerStyle: { + backgroundColor: theme.color.extendedPrimary100, + }, + avatarStyle: { + containerStyle: { + backgroundColor: theme.color.extendedPrimary500, + borderRadius: 8, + }, + imageStyle: { + borderRadius: 8, + }, + }, + declineCallButtonStyle: { + backgroundColor: theme.color.staticWhite, + }, + declineCallTextStyle: { + color: theme.color.error, + }, + acceptCallButtonStyle: { + backgroundColor: theme.color.primary, + }, + }} + /> + ); +} +``` -Use Cases: +### Visibility Props -* Add custom accept/reject buttons. -* Show a mute button before answering. -* Display a text response option (e.g., "Can’t talk now") +| Property | Description | Code | +| --- | --- | --- | +| `disableSoundForCalls` | Disable/enable the sound of incoming calls | `disableSoundForCalls?: boolean` | +| `customSoundForCalls` | Set custom sound for incoming calls | `customSoundForCalls?: string` | -```javascript -import { CometChatIncomingCall } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - - {callReceived && ( - { - setCallReceived(false); - }} - TrailingView={(call: CometChat.Call | CometChat.CustomMessage) => { - //return JSX; - }} - /> - )} - -); -``` +--- -*** +## Next Steps + + + + Display and manage outgoing calls + + + Add voice and video call buttons to your UI + + + Overview of all calling features + + + Customize the appearance of UI Kit components + + diff --git a/ui-kit/react-native/localize.mdx b/ui-kit/react-native/localize.mdx index f151579d3..dc1dd85e7 100644 --- a/ui-kit/react-native/localize.mdx +++ b/ui-kit/react-native/localize.mdx @@ -1,50 +1,73 @@ --- -title: "Localize" +title: "Localization" +sidebarTitle: "Localize" +description: "Configure multi-language localization, custom translations, and automatic device language detection in CometChat React Native UI Kit." --- -## Overview + -CometChat UI Kit provides language localization to adapt to the language of a specific country or region. This document outlines how a developer can customize localization provided by UI Kit to their requirements. +| Field | Value | +| --- | --- | +| Goal | Add multi-language support with automatic device language detection | +| Provider | `CometChatI18nProvider` — wrap app to enable localization | +| Import | `import { CometChatI18nProvider } from "@cometchat/chat-uikit-react-native";` | +| Auto-detect | `` | +| Set language | `selectedLanguage="fr"` — manually set language code | +| Override strings | `translations={{ "en-US": { CHATS: "My Chats" } }}` | +| Add language | `translations={{ "custom": { CHATS: "Welcome" } }}` with `selectedLanguage="custom"` | +| Use in components | `const { t } = useCometChatTranslation(); t("CHATS")` | +| Supported languages | 19: en-US, en-GB, zh, zh-TW, es, hi, ru, pt, ms, fr, de, sv, lt, hu, it, ko, ja, nl, tr | +| Dependency | Requires `react-native-localize` package for auto-detection | -`CometChatI18nProvider` is a context provider that enables developers to supply custom translations and manage localization across their application. + -Presently, the UI Kit supports 19 languages for localization, which are: +The `CometChatI18nProvider` manages multi-language localization for the UI Kit. It handles automatic language detection, manual language switching, and custom translations. -* English (en, en-US, en-GB) -* Chinese (zh, zh-TW) -* Spanish (es) -* Hindi (hi) -* Russian (ru) -* Portuguese (pt) -* Malay (ms) -* French (fr) -* German (de) -* Swedish (sv) -* Lithuanian (lt) -* Hungarian (hu) -* Italian (it) -* Korean (ko) -* Japanese (ja) -* Dutch (nl) -* Turkish (tr) - -## Customization - -The `CometChatI18nProvider` component enables developers to pass custom translations. Developers can override existing translations or add new ones. + +Prerequisites: +1. Install `react-native-localize`: `npm install react-native-localize` +2. Wrap your app with `CometChatI18nProvider` inside `CometChatThemeProvider` +3. Without the provider wrapper, automatic language detection won't work + -The `CometChatI18nProvider` component accepts the following props: +--- -* `selectedLanguage`: The language to use for translations. Defaults to the user's device language, or defaults to English if `autoDetectLanguage` is false. -* `autoDetectLanguage`: Whether to automatically detect the user's device language. -* `translations`: An object containing the translation overrides for each language. +## Supported Languages + +| Language | Code | +| --- | --- | +| English (United States) | `en-US` | +| English (United Kingdom) | `en-GB` | +| Chinese | `zh` | +| Chinese (Traditional) | `zh-TW` | +| Spanish | `es` | +| Hindi | `hi` | +| Russian | `ru` | +| Portuguese | `pt` | +| Malay | `ms` | +| French | `fr` | +| German | `de` | +| Swedish | `sv` | +| Lithuanian | `lt` | +| Hungarian | `hu` | +| Italian | `it` | +| Korean | `ko` | +| Japanese | `ja` | +| Dutch | `nl` | +| Turkish | `tr` | -Users can provide new languages by adding a new key in the translations object. +--- - +## Provider Props -To ensure the app dynamically adapts to the device's language settings and properly displays localized content, it must be wrapped in the CometChatI18nProvider. Without this wrapper, automatic language detection and custom translations will not work in the app's UI. +| Prop | Type | Description | +| --- | --- | --- | +| `selectedLanguage` | `string` | Language code to use. Defaults to device language or English | +| `autoDetectLanguage` | `boolean` | Auto-detect device language. Default: `true` | +| `translations` | `object` | Custom translation overrides per language | +| `fallbackLanguage` | `string` | Fallback language if selected is unavailable | - +--- ## Prerequisites @@ -67,20 +90,18 @@ Here is how you can implement custom localization: ```ts -import React from 'react'; -import { SafeAreaView } from 'react-native'; -import { - CometChatThemeProvider, - CometChatI18nProvider, -} from '@cometchat/chat-uikit-react-native'; +import React from "react"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; const App = () => { return ( - - + + {/* Other Components */} @@ -96,33 +117,34 @@ const App = () => { ```ts -import React from 'react'; -import { SafeAreaView } from 'react-native'; -import { - CometChatThemeProvider, - CometChatI18nProvider, -} from '@cometchat/chat-uikit-react-native'; +import React from "react"; +import { SafeAreaView } from "react-native-safe-area-context"; +import { + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; const App = () => { const translations = { // Overridden translations "en-US": { - CHATS: 'Welcome to the CometChat App', + CHATS: "Welcome to the CometChat App", }, "en-GB": { - CHATS: 'Welcome to CometChat', + CHATS: "Welcome to CometChat", }, custom: { - CHATS: "Welcome" + CHATS: "Welcome", }, }; return ( - + + translations={translations} + > {/* Other Components */} @@ -138,26 +160,25 @@ const App = () => { ```ts -import React from 'react'; -import { View, Text, TouchableOpacity } from 'react-native'; -import { - useCometChatTranslation -} from '@cometchat/chat-uikit-react-native'; +import React from "react"; +import { View, Text, TouchableOpacity } from "react-native"; +import { useCometChatTranslation } from "@cometchat/chat-uikit-react-native"; const CustomComponent = () => { const { t } = useCometChatTranslation(); return ( - + {t("WELCOME_MESSAGE")} - { console.log(t("BUTTON_CLICKED")); - }}> - + }} + > + {t("CLICK_HERE")} @@ -168,7 +189,24 @@ const CustomComponent = () => { -CometChat UI-Kit provides a `useCometChatTranslation` hook to access translations within components, which can be used when developing custom components. +CometChat UI Kit provides a `useCometChatTranslation` hook to access translations within components, which can be used when developing custom components. + +--- + +## Methods + +### useCometChatTranslation + +Hook to access translations within components. + +```ts +import { useCometChatTranslation } from "@cometchat/chat-uikit-react-native"; + +const { t } = useCometChatTranslation(); +const translatedText = t("CHATS"); // Returns localized string +``` + +--- ## Customization Capabilities @@ -179,8 +217,26 @@ Below are the things which the developer can customize: * **Add custom strings** (`translations`): A developer can add custom strings in the localization for a particular language. * **Add a new language** (`translations`): The developer can add completely new languages. * **Disable auto detection** (`autoDetectLanguage`): The developer can disable auto detection of device language. -* **Handle missing keys** : The developer can handle missing localization key. -* **Set fallback language** (`fallbackLanguage`): The developer can set fallback language. +* **Handle missing keys**: The developer can handle missing localization keys. +* **Set fallback language** (`fallbackLanguage`): The developer can set a fallback language. By using the `CometChatI18nProvider` component and `useCometChatTranslation` hook, you can provide a user-friendly, localized experience to your users, enhancing the overall user experience within your application. +--- + +## Next Steps + + + + Learn how CometChatThemeProvider manages light and dark modes + + + Manage audio playback for incoming and outgoing events + + + Explore all available UI Kit components + + + Set up CometChat UI Kit in your React Native app + + diff --git a/ui-kit/react-native/mentions-formatter-guide.mdx b/ui-kit/react-native/mentions-formatter-guide.mdx index a0917f5ea..7e81c3d1d 100644 --- a/ui-kit/react-native/mentions-formatter-guide.mdx +++ b/ui-kit/react-native/mentions-formatter-guide.mdx @@ -1,7 +1,22 @@ --- title: "Mentions Formatter" +description: "Format and style @mentions in chat messages with customizable text styles and click handlers using CometChatMentionsFormatter." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key class | `CometChatMentionsFormatter` (extends `CometChatTextFormatter`) | +| Required setup | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Format and style @mentions in chat messages with customizable text styles and click handlers | +| Features | Mention formatting, customizable styles, user/group member mentions, mention list generation, click handling | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/sample) | +| Related | [ShortCut Formatter](/ui-kit/react-native/shortcut-formatter-guide) · [Custom Text Formatter](/ui-kit/react-native/custom-text-formatter-guide) · [All Guides](/ui-kit/react-native/guide-overview) | + + + ## Overview The `CometChatMentionsFormatter` class is a part of the CometChat UI Kit, a ready-to-use chat UI component library for integrating CometChat into your Android applications. This class provides functionality to format mentions within text messages displayed in the chat interface. Mentions allow users to reference other users within a conversation, providing a convenient way to direct messages or involve specific participants. @@ -20,7 +35,7 @@ To integrate the `CometChatMentionsFormatter` class into your application: 1. **Initialization**: Create an instance of the `CometChatMentionsFormatter` class and configure it with desired settings, such as mention text styles and limit settings. -2. **Set Mention Listeners**: Set listeners for handling mention click events (`setOnMentionCLick`). +2. **Set Mention Listeners**: Set listeners for handling mention click events (`setOnMentionClick`). 3. **Customization**: Customize the appearance and behavior of mentions by adjusting the text styles, colors, and other formatting properties as needed. @@ -41,6 +56,8 @@ textFormatters.push(mentionsFormatter); +--- + ## Actions [Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. @@ -65,13 +82,12 @@ Setting a listener for mention-click events in Message Bubbles enhances interact - -```tsx + +```tsx lines import React from "react"; import { CometChat } from '@cometchat/chat-sdk-react-native'; -import { CometChatMessages, CometChatMentionsFormatter } from '@cometchat/chat-uikit-react-native'; -import Toast from 'react-native-toast-message'; +import { CometChatMessageList, CometChatMentionsFormatter } from '@cometchat/chat-uikit-react-native'; function App(): React.JSX.Element { const [chatUser, setChatUser] = React.useState(); @@ -92,19 +108,15 @@ function App(): React.JSX.Element { user = mentionedUsers[i]; } } - Toast.show({ - text1: user?.getName(), - text2: "mention" - }); + console.log("Mention clicked:", user?.getName()); }) return ( <> - { chatUser && } - ); } @@ -114,6 +126,8 @@ function App(): React.JSX.Element { +--- + ## Customization | Methods | Description | Code | @@ -122,6 +136,8 @@ function App(): React.JSX.Element { | **Set GroupMembersRequestBuilder** | Sets the builder for fetching users or group members. | `setSearchRequestBuilder(requestBuilder: CometChat.UsersRequestBuilder` \| `CometChat.GroupMembersRequestBuilder)` | | **Set OnMentionClick** | Sets a listener for mention click in Message Bubbles events. | `setOnMentionClick(callBack: (message: CometChat.BaseMessage, uid: string) => void);` | +--- + ## Advance For advanced-level customization, you can set the style of the Mentions formatters. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your formatters style. @@ -133,15 +149,15 @@ MentionTextStyle is a class that is used to provide over all styling to a partic | Methods | Type | Description | | ------------------------- | --------- | ------------------------------------------------------------- | | **textStyle** | TextStyle | The text style to be applied to mentions | -| **loggedInUserTextStyle** | TextStyle | The text style to be applied to the logged-in user's mentions | +| **selfTextStyle** | TextStyle | The text style to be applied to the logged-in user's mentions | - -```tsx + +```tsx lines import React from "react"; import { CometChat } from '@cometchat/chat-sdk-react-native'; -import { CometChatMessages, CometChatMentionsFormatter, TextStyle, MentionTextStyle } from '@cometchat/chat-uikit-react-native'; +import { CometChatMessageList, CometChatMentionsFormatter, TextStyle, MentionTextStyle } from '@cometchat/chat-uikit-react-native'; function App(): React.JSX.Element { const [chatUser, setChatUser] = React.useState(); @@ -154,7 +170,7 @@ function App(): React.JSX.Element { const mentionsFormatter = new CometChatMentionsFormatter(); - const loggedInUserTextStyle : TextStyle = { + const selfTextStyle : TextStyle = { color: "red", fontWeight: "bold" } @@ -164,7 +180,7 @@ function App(): React.JSX.Element { } const mentiontextStyle : MentionTextStyle = { - loggedInUserTextStyle: loggedInUserTextStyle, + selfTextStyle: selfTextStyle, textStyle: otherUsersStyle } @@ -172,11 +188,10 @@ function App(): React.JSX.Element { return ( <> - { chatUser && } - ); } @@ -185,3 +200,22 @@ function App(): React.JSX.Element { + +--- + +## Next Steps + + + + Create custom text shortcuts for quick message composition + + + Auto-detect and style URLs as clickable links + + + Browse all feature and formatter guides + + + Customize how messages are displayed + + diff --git a/ui-kit/react-native/message-bubble-styling.mdx b/ui-kit/react-native/message-bubble-styling.mdx index 30ff8e37c..1ed6fb803 100644 --- a/ui-kit/react-native/message-bubble-styling.mdx +++ b/ui-kit/react-native/message-bubble-styling.mdx @@ -1,5 +1,57 @@ --- title: "Message Bubble Styling" +description: "Customize the appearance of incoming and outgoing message bubbles in CometChat React Native UI Kit, including text, image, video, audio, file, poll, and other message types." +--- + + + +| Field | Value | +| --- | --- | +| Goal | Customize incoming/outgoing message bubble appearance | +| Provider | `CometChatThemeProvider` — pass bubble styles in `theme.messageListStyles` | +| Import | `import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native";` | +| Incoming bubbles | `messageListStyles: { incomingMessageBubbleStyles: { containerStyle: { backgroundColor: "#FEEDE1" } } }` | +| Outgoing bubbles | `messageListStyles: { outgoingMessageBubbleStyles: { containerStyle: { backgroundColor: "#F76808" } } }` | +| Bubble types | `textBubbleStyles`, `imageBubbleStyles`, `videoBubbleStyles`, `audioBubbleStyles`, `fileBubbleStyles`, `pollBubbleStyles`, `stickerBubbleStyles`, `assistantBubbleStyles` | +| Special bubbles | `deletedBubbleStyles`, `collaborativeBubbleStyles`, `groupCallBubbleStyles`, `linkPreviewBubbleStyles` | +| Action bubbles | `groupActionBubbleStyles`, `callActionBubbleStyles`, `userCallBubbleStyles` | +| Precedence | Specific bubble style > Container style > Default (deep merge) | +| Source | [GitHub theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts) | + + + +Customize message bubble appearance by passing bubble styles in `theme.messageListStyles`. + + +Prerequisites: +1. Wrap your app with `CometChatThemeProvider` +2. Bubble styles are passed via `theme={{ light: { messageListStyles: { ... } } }}` +3. Specific bubble type styles (e.g., `textBubbleStyles`) override general `containerStyle` + + +--- + +## Bubble Style Keys + +| Bubble Type | Style Key | Common Properties | +| --- | --- | --- | +| All incoming | `incomingMessageBubbleStyles` | `containerStyle`, `avatarStyle`, `receiptStyles`, `reactionStyles` | +| All outgoing | `outgoingMessageBubbleStyles` | `containerStyle`, `avatarStyle`, `receiptStyles`, `reactionStyles` | +| Text | `textBubbleStyles` | `containerStyle`, `textStyle`, `mentionsStyle` | +| AI Assistant | `assistantBubbleStyles` | `containerStyle`, `textStyle`, `copyButtonStyle`, `errorContainerStyle` | +| Image | `imageBubbleStyles` | `containerStyle`, `imageStyle` | +| Video | `videoBubbleStyles` | `containerStyle`, `playIconStyle`, `playIconContainerStyle` | +| Audio | `audioBubbleStyles` | `containerStyle`, `playIconStyle`, `waveStyle` | +| File | `fileBubbleStyles` | `containerStyle`, `titleStyle`, `subtitleStyle`, `downloadIconStyle` | +| Sticker | `stickerBubbleStyles` | `containerStyle`, `imageStyle` | +| Poll | `pollBubbleStyles` | `containerStyle`, `progressBarStyle`, `selectedIconStyle`, `titleStyle` | +| Link Preview | `linkPreviewBubbleStyles` | `containerStyle`, `bodyStyle`, `headerImageContainerStyle` | +| Collaborative | `collaborativeBubbleStyles` | `containerStyle`, `iconStyle`, `buttonTextStyle`, `dividerStyle` | +| Meet Call | `meetCallBubbleStyles` | `containerStyle`, `iconStyle`, `dividerStyle` | +| Deleted | `deletedBubbleStyles` | `containerStyle`, `icon` | +| Group Action | `groupActionBubbleStyles` | `containerStyle`, `textStyle` | +| Call Action | `callActionBubbleStyles` | `containerStyle`, `textStyle`, `iconStyle`, `missedCallContainerStyle` | + --- ## Overview @@ -79,17 +131,16 @@ interface CometChatTheme { -* DeepPartial is an internal utility that ensures all style properties are optional, allowing only the required fields to be overridden. +* `DeepPartial` is an internal utility that ensures all style properties are optional, allowing only the required fields to be overridden. * When customizing theme properties, whether by overriding specific properties or supplying a completely custom theme, the provided values will be deeply merged with the default theme. This means that only the specified properties will be overridden, while all other properties will retain their default values. Additionally, if a style is passed through props, it will take priority over the style provided via the theme. -In the code snippet below, incoming text message bubbles will have a background color of `#f90ac6`, while all other incoming message bubbles will have `#f90a4e`. The `paddingHorizontal` value set in `incomingMessageBubbleStyles.containerStyle` will also apply to all incoming message bubbles, unless explicitly overridden for a specific bubble type. For instance, you can set `incomingMessageBubbleStyles`.`textBubbleStyles.containerStyle.paddingHorizontal` to `0` if you want to remove horizontal padding for text bubbles. +In the code snippet below, incoming text message bubbles will have a background color of `#f90ac6`, while all other incoming message bubbles will have `#f90a4e`. The `paddingHorizontal` value set in `incomingMessageBubbleStyles.containerStyle` will also apply to all incoming message bubbles, unless explicitly overridden for a specific bubble type. For instance, you can set `incomingMessageBubbleStyles.textBubbleStyles.containerStyle.paddingHorizontal` to `0` if you want to remove horizontal padding for text bubbles. ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( ; + > ); ``` ## Message Bubbles -Message bubbles are core elements of the messaging interface. Their collective appearance can be customized to create a consistent design, including color, shape, and overall style for both outgoing and incoming messages. The message bubbles' styles can be customized by extending the predefined styles in your themes.xml file. +Message bubbles are core elements of the messaging interface. Their collective appearance can be customized to create a consistent design, including color, shape, and overall style for both outgoing and incoming messages. The message bubbles' styles can be customized by extending the predefined styles in your theme. **Customizing Incoming Message Bubble** @@ -128,9 +179,8 @@ Message bubbles are core elements of the messaging interface. Their collective a ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( ; + > ); ``` @@ -157,9 +207,8 @@ return ( ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -202,39 +251,38 @@ Text bubbles display plain text messages. These are the most common bubble type **Customizing Incoming and Outgoing Bubbles** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` -To know more such attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v5/chatuikit/src/main/res/values/attr_cometchat_text_bubble.xml). +To learn more about such attributes, refer to the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). ### Link Preview Bubble @@ -255,51 +303,50 @@ The Link Preview Bubble is designed to display a preview of links shared in mess **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -324,35 +371,34 @@ Image bubbles display images shared within a conversation. **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -373,35 +419,34 @@ Video bubbles display video messages or clips in a chat. **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -426,44 +471,43 @@ Audio bubbles represent audio messages or voice recordings. **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -488,35 +532,34 @@ File bubbles are used to display shared files, such as documents, PDFs, or sprea **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -541,35 +584,34 @@ Sticker bubbles display stickers shared in a conversation, enhancing visual expr **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -594,42 +636,41 @@ Poll bubbles represent polls shared within the chat, showing options and results **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -654,57 +695,56 @@ Collaborative bubbles display collaborative content, such as shared documents or **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -729,54 +769,53 @@ Meet call bubbles display call-related actions and statuses in the chat interfac **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -801,37 +840,36 @@ Delete bubbles are used to display messages that have been deleted by the sender **Customizing Incoming and Outgoing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -856,45 +894,44 @@ Call action bubbles display call-related actions, such as missed calls, in the c **Customizing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` @@ -919,52 +956,35 @@ Action bubbles provide a customizable interface for displaying a variety of acti **Customizing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} - ; + {/*your component*/} + ); ``` To learn more about such attributes, refer to the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). - - ### AI Assistant Bubble AI Assistant bubbles display messages and interactions from an AI assistant within the chat interface. @@ -984,9 +1004,8 @@ AI Assistant bubbles display messages and interactions from an AI assistant with **Customizing Bubble** ```tsx -import { - CometChatThemeProvider, -} from "@cometchat/chat-uikit-react-native"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + //other code return ( - {/*your component*/} + {/*your component*/} ); ``` To learn more about such attributes, refer to the [theme interface](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts). +--- + +## Next Steps + + + + Learn how CometChatThemeProvider manages light and dark modes + + + Customize primary, neutral, alert, and other color tokens + + + Style individual UI Kit components like Conversations and Users + + + Explore the Message List component and its customization options + + diff --git a/ui-kit/react-native/message-composer.mdx b/ui-kit/react-native/message-composer.mdx index 608ee9657..64aca17ef 100644 --- a/ui-kit/react-native/message-composer.mdx +++ b/ui-kit/react-native/message-composer.mdx @@ -1,290 +1,312 @@ --- title: "Message Composer" +description: "Compose and send messages including text, media, and attachments with CometChatMessageComposer component in React Native UI Kit." --- -## Overview + +```json +{ + "component": "CometChatMessageComposer", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatMessageComposer } from \"@cometchat/chat-uikit-react-native\";", + "description": "Rich text input for composing and sending text, media, attachments, mentions, voice notes, and custom messages.", + "primaryOutput": { + "prop": "onSendButtonPress", + "type": "(message: CometChat.BaseMessage) => void" + }, + "props": { + "data": { + "user": { "type": "CometChat.User", "default": "undefined" }, + "group": { "type": "CometChat.Group", "default": "undefined" }, + "parentMessageId": { "type": "number", "default": "undefined" }, + "initialComposertext": { "type": "string", "default": "\"\"" } + }, + "callbacks": { + "onSendButtonPress": "(message: CometChat.BaseMessage) => void", + "onTextChange": "(text: string) => void", + "onError": "(error: CometChat.CometChatException) => void" + }, + "visibility": { + "hideVoiceRecordingButton": { "type": "boolean", "default": false }, + "hideCameraOption": { "type": "boolean", "default": false }, + "hideImageAttachmentOption": { "type": "boolean", "default": false }, + "hideVideoAttachmentOption": { "type": "boolean", "default": false }, + "hideAudioAttachmentOption": { "type": "boolean", "default": false }, + "hideFileAttachmentOption": { "type": "boolean", "default": false }, + "hidePollsAttachmentOption": { "type": "boolean", "default": false }, + "hideCollaborativeDocumentOption": { "type": "boolean", "default": false }, + "hideCollaborativeWhiteboardOption": { "type": "boolean", "default": false }, + "hideAttachmentButton": { "type": "boolean", "default": false }, + "hideStickersButton": { "type": "boolean", "default": false }, + "hideSendButton": { "type": "boolean", "default": false }, + "hideAuxiliaryButtons": { "type": "boolean", "default": false } + }, + "configuration": { + "imageQuality": { "type": "number (1-100)", "default": 20 }, + "auxiliaryButtonsAlignment": { "type": "\"left\" | \"right\"", "default": "\"left\"" } + }, + "sound": { + "disableSoundForOutgoingMessages": { "type": "boolean", "default": false }, + "customSoundForOutgoingMessage": { "type": "audio source", "default": "built-in" } + }, + "behavior": { + "disableTypingEvents": { "type": "boolean", "default": false }, + "disableMentions": { "type": "boolean", "default": false }, + "disableMentionAll": { "type": "boolean", "default": false }, + "mentionAllLabel": { "type": "string", "default": "\"all\"" } + }, + "viewSlots": { + "HeaderView": "({ user, group }: { user?: CometChat.User, group?: CometChat.Group }) => JSX.Element", + "AuxiliaryButtonView": "({ user, group, composerId }: { user?: CometChat.User, group?: CometChat.Group, composerId: string | number }) => JSX.Element", + "SendButtonView": "({ user, group, composerId }: { user?: CometChat.User, group?: CometChat.Group, composerId: string | number }) => JSX.Element" + }, + "formatting": { + "textFormatters": { + "type": "CometChatTextFormatter[]", + "default": "default formatters from data source" + }, + "attachmentOptions": { + "type": "CometChatMessageComposerAction[]", + "note": "Custom attachment options list" + }, + "addAttachmentOptions": { + "type": "CometChatMessageComposerAction[]", + "note": "Additional attachment options to append to defaults" + } + } + }, + "events": [ + { + "name": "ccMessageSent", + "payload": "{ message: CometChat.BaseMessage, status: string }", + "description": "Triggers when a message is sent with status: inprogress, success, or error" + }, + { + "name": "ccMessageEdited", + "payload": "{ message: CometChat.BaseMessage, status: string }", + "description": "Triggers when a message is edited with status: inprogress, success, or error" + }, + { + "name": "ccMessageLiveReaction", + "payload": "object", + "description": "Triggers when user clicks on live reaction" + } + ], + "compositionExample": { + "description": "Message composer wired with message header and list for complete chat view", + "components": [ + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "Pass user or group prop to composer -> onSendButtonPress fires with CometChat.BaseMessage -> message appears in MessageList" + } +} +``` + + +## Where It Fits -MessageComposer is a [Component](/ui-kit/react-native/components-overview#components) that enables users to write and send a variety of messages, including text, image, video, and custom messages. +`CometChatMessageComposer` is a [Component](/ui-kit/react-native/components-overview#components) that enables users to write and send a variety of messages, including text, image, video, and custom messages. Features such as **Live Reaction**, **Attachments**, and **Message Editing** are also supported. -Features such as **Live Reaction**, **Attachments**, and **Message Editing** are also supported by it. +Wire it alongside `CometChatMessageHeader` and `CometChatMessageList` to build a standard chat view. -## Usage - -### Integration +--- -The following code snippet illustrates how you can directly incorporate the `CometChatMessageComposer` component into your app. +## Minimal Render - - -```tsx +```tsx lines import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -//code -return ; -``` - - - - - -### Actions - -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. - -##### onSendButtonPress -The `onSendButtonPress` event gets activated when the send message button is clicked. It has a predefined function of sending messages entered in the composer `EditText`. However, you can overide this action with the following code snippet. +function MessageComposerDemo() { + return ; +} - - -```tsx -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -//code -const onSendButtonPressHandler = (message: CometChat.BaseMessage) => { - //code -}; -return ( - -); +export default MessageComposerDemo; ``` - - - - -##### onError - -This action doesn't change the behavior of the component but rather listens for any errors that occur in the `CometChatMessageComposer` component. - - - -```tsx -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -//code -const onError = (error: CometChat.CometChatException) => { - //handle error -}; -return ( - -); -``` +--- - +## Actions and Events - +### Callback Props -##### onTextChange +#### onSendButtonPress -Function triggered whenever the message input's text value changes, enabling dynamic text handling. +Fires when the send message button is clicked. Overrides the default send behavior. - - -```tsx -import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -//code -const onTextChange = (text: string) => { - //code -}; -return ( - -); +```tsx lines +onSendButtonPress?: (message: CometChat.BaseMessage) => void ``` - - - - -*** +```tsx lines +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -### Filters +function ComposerWithCustomSend() { + const onSendButtonPressHandler = (message: CometChat.BaseMessage) => { + console.log("Custom send:", message); + }; -MessageComposer component does not have any available filters. + return ( + + ); +} +``` -*** +#### onError -### Events +Fires on internal errors (network failure, auth issue, SDK exception). -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +```tsx lines +onError?: (error: CometChat.CometChatException) => void +``` -The list of events emitted by the Messages component is as follows. +```tsx lines +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -| Event | Description | -| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -| **ccMessageSent** | Triggers whenever a loggedIn user sends any message, it will have two states such as: `inprogress`, `success` & `error` | -| **ccMessageEdited** | Triggers whenever a loggedIn user edits any message from the list of messages. It will have two states such as: `inprogress`, `success` & `error` | -| **ccMessageLiveReaction** | Triggers whenever a loggedIn clicks on live reaction | +function ComposerWithErrorHandler() { + return ( + { + console.error("Composer error:", error); + }} + /> + ); +} +``` -Adding `CometChatMessageEvents` Listener's +#### onTextChange - - -```js -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +Fires as the user types in the composer input. -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - ccMessageSent: (item) => { - //code - }, -}); +```tsx lines +onTextChange?: (text: string) => void +``` -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - ccMessageEdited: (item) => { - //code - }, -}); +```tsx lines +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - ccMessageLiveReaction: (item) => { - //code - }, -}); +function ComposerWithTextTracking() { + return ( + { + console.log("Text changed:", text); + }} + /> + ); +} ``` - +### Global UI Events - +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Add listeners and remove them on cleanup. -*** +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccMessageSent` | A message is sent | `{ message: CometChat.BaseMessage, status: string }` | +| `ccMessageEdited` | A message is edited | `{ message: CometChat.BaseMessage, status: string }` | +| `ccMessageLiveReaction` | User clicks on live reaction | `object` | -Removing `CometChatMessageEvents` Listener's +When to use: sync external UI with message state changes. For example, update a notification badge when messages are sent, or trigger analytics when a message is edited. - - -```js +```tsx lines +import { useEffect } from "react"; import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.removeMessageListener("MESSAGE_LISTENER_ID"); +function useComposerEvents() { + useEffect(() => { + const listenerId = "MESSAGE_COMPOSER_EVENTS_" + Date.now(); + + CometChatUIEventHandler.addMessageListener(listenerId, { + ccMessageSent: (item) => { + console.log("Message sent:", item); + }, + ccMessageEdited: (item) => { + console.log("Message edited:", item); + }, + ccMessageLiveReaction: (item) => { + console.log("Live reaction:", item); + }, + }); + + return () => { + CometChatUIEventHandler.removeMessageListener(listenerId); + }; + }, []); +} ``` - - - - -*** + +In React 18 StrictMode, `useEffect` runs twice on mount in development. The component handles listener cleanup internally, but any additional listeners added alongside the component need cleanup in the `useEffect` return function to avoid duplicate event handling. + -## Customization - -To fit your app's design requirements, you can customize the appearance of the MessageComposer component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -### Style - -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. - - - - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets - -| Property | Description | Code | -| ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | -| **user** | Used to pass user object of which header specific details will be show | `user={chatUser}` | -| **group** | Used to pass group object of which header specific details will be shown | `group={chatGroup}` | -| **disableTypingEvents** | Used to disable/enable typing events , default false | `disableTypingEvents={true}` | -| **disableSoundForOutgoingMessages** | Used to toggle sound for outgoing messages | `disableSoundForOutgoingMessages={true}` | -| **initialComposertext** | Used to set predefined text | `initialComposertext="Your custom text"` | -| **customSoundForOutgoingMessage** | Used to give custom sounds to outgoing messages | `customSoundForOutgoingMessage="your custom sound for messages"` | -| **hideVoiceRecordingButton** | used to hide the voice recording option. | `hideVoiceRecording={true}` | -| **hideCameraOption** | toggle visibility of camera option from the attachment options. | `hideCameraOption={true}` | -| **hideImageAttachmentOption** | toggle visibility of image attachment options. | `hideImageAttachmentOption={true}` | -| **hideVideoAttachmentOption** | toggle visibility of video attachment options. | `hideVideoAttachmentOption={true}` | -| **hideAudioAttachmentOption** | toggle visibility of audio attachment options. | `hideAudioAttachmentOption={true}` | -| **hideFileAttachmentOption** | toggle visibility of file attachment options. | `hideFileAttachmentOption={true}` | -| **hidePollsAttachmentOption** | toggle visibility of file polls attachment options. | `hidePollsAttachmentOption={true}` | -| **hideCollaborativeDocumentOption** | toggle visibility of file Collaborative Document Option. | `hideCollaborativeDocumentOption={true}` | -| **hideCollaborativeWhiteboardOption** | toggle visibility of file Collaborative Whiteboard Option. | `hideCollaborativeWhiteboardOption={true}` | -| **hideAttachmentButton** | toggle visibility of hide attachment option. | `hideAttachmentButton={true}` | -| **hideStickersButton** | toggle visibility of hide stickers option. | `hideStickersButton={true}` | -| **hideSendButton** | toggle visibility of send button option. | `hideSendButton={true}` | -| **hideAuxiliaryButtons** | toggle visibility of Auxiliary button option. | `hideAuxiliaryButtons={true}` | -| **disableMentions** | Sets whether mentions in text should be disabled. Processes the text formatters If there are text formatters available and the disableMentions flag is set to true, it removes any formatters that are instances of CometChatMentionsFormatter. | `disableMentions={true}` | - -*** +--- -### Advanced +## Custom View Slots -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +Each slot replaces a section of the default UI. Slots that accept parameters receive the relevant data for customization. -*** +| Slot | Signature | Replaces | +| --- | --- | --- | +| `HeaderView` | `({ user, group }) => JSX.Element` | Area above the composer input | +| `AuxiliaryButtonView` | `({ user, group, composerId }) => JSX.Element` | Sticker button area | +| `SendButtonView` | `({ user, group, composerId }) => JSX.Element` | Send button | +| `attachmentOptions` | `CometChatMessageComposerAction[]` | Default attachment options list | +| `textFormatters` | `CometChatTextFormatter[]` | Text formatting in composer | -#### TextFormatters +### textFormatters -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/react-native/mentions-formatter-guide) +Custom text formatters for the composer input. To configure the existing Mentions look and feel check out [CometChatMentionsFormatter](/ui-kit/react-native/mentions-formatter-guide). - - -```tsx +```tsx lines import { CometChatMessageComposer, CometChatTextFormatter, CometChatMentionsFormatter, } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTextFomatters = () => { + +const getTextFormatters = () => { const textFormatters: CometChatTextFormatter[] = []; const mentionsFormatter = new CometChatMentionsFormatter(); mentionsFormatter.setMentionsStyle({ - textStyle: { - color: "#D6409F", - }, - selfTextStyle: { - color: "#30A46C", - }, + textStyle: { color: "#D6409F" }, + selfTextStyle: { color: "#30A46C" }, }); textFormatters.push(mentionsFormatter); return textFormatters; }; + return ( ); ``` - - - - -**Example** - -#### AttachmentOptions +### attachmentOptions -By using `attachmentOptions`, you can set a list of custom `MessageComposerActions` for the MessageComposer Component. This will override the existing list of `MessageComposerActions`. +Override the default attachment options with custom actions. - - -```tsx -import { - CometChatMessageComposer, - CometChatTextFormatter, - CometChatMentionsFormatter, -} from "@cometchat/chat-uikit-react-native"; +```tsx lines +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code + const getCustomAttachmentOptions = ({ user, group, @@ -294,48 +316,77 @@ const getCustomAttachmentOptions = ({ group?: CometChat.Group; composerId: Map; }): CometChatMessageComposerAction[] => { - let attachmentOptions: CometChatMessageComposerAction[] = []; - attachmentOptions.push({ - id: "location", - icon: LocationIcon, - title: "Share Location", - style: { iconStyle: { tintColor: "grey" } }, - onPress: () => { - //handleOnPress + return [ + { + id: "location", + icon: LocationIcon, + title: "Share Location", + style: { iconStyle: { tintColor: "grey" } }, + onPress: () => { + // handle location share + }, }, - }); - return attachmentOptions; + ]; }; + return ( ); ``` - - - - -**Example** - -*** +### addAttachmentOptions + +Extends the default attachment options with additional actions. + +```tsx lines +import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const getAdditionalAttachmentOptions = ({ + user, + group, + composerId, +}: { + user?: CometChat.User; + group?: CometChat.Group; + composerId: Map; +}): CometChatMessageComposerAction[] => { + return [ + { + id: "location", + icon: LocationIcon, + title: "Share Location", + style: { iconStyle: { tintColor: "grey" } }, + onPress: () => { + // handle location share + }, + }, + ]; +}; + +return ( + +); +``` -#### AuxiliaryButtonView +### AuxiliaryButtonView -You can insert a custom view into the MessageComposer component to add additional functionality using the following method. +Replace the sticker button area with a custom view. - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -//code +import { TouchableOpacity, Image, StyleSheet } from "react-native"; const styles = StyleSheet.create({ button: { @@ -356,17 +407,12 @@ const customAuxiliaryButtonView = ({ group, composerId, }: { - user?: CometChat.User, - group?: CometChat.Group, - composerId: string | number, + user?: CometChat.User; + group?: CometChat.Group; + composerId: string | number; }): JSX.Element => { return ( - { - /* code */ - }} - > + {}}> ); @@ -380,30 +426,23 @@ return ( ); ``` - - - - -Please note that the MessageComposer Component utilizes the AuxiliaryButton to provide sticker functionality. Overriding the AuxiliaryButton will subsequently replace the sticker functionality. - -**Example** + +The MessageComposer Component utilizes the AuxiliaryButton to provide sticker functionality. Overriding the AuxiliaryButton will replace the sticker functionality. + -*** - -#### SendButtonView +### SendButtonView -You can set a custom view in place of the already existing send button view. Using the following method. +Replace the send button with a custom view. - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -//code +import { TouchableOpacity, Image, StyleSheet } from "react-native"; + const styles = StyleSheet.create({ button: { height: 25, @@ -423,17 +462,12 @@ const customSendButtonView = ({ group, composerId, }: { - user?: CometChat.User, - group?: CometChat.Group, - composerId: string | number, + user?: CometChat.User; + group?: CometChat.Group; + composerId: string | number; }): JSX.Element => { return ( - { - /* code */ - }} - > + {}}> ); @@ -447,28 +481,19 @@ return ( ); ``` - - - - -**Example** - -*** +### HeaderView -#### HeaderView +Custom view above the composer input. -You can set custom headerView to the MessageComposer component using the following method - - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatMessageComposer } from "@cometchat/chat-uikit-react-native"; -//code +import { View, Text, StyleProp, ViewStyle } from "react-native"; + const viewStyle: StyleProp = { flexDirection: "row", alignItems: "flex-start", @@ -488,8 +513,8 @@ const customHeaderView = ({ user, group, }: { - user?: CometChat.User, - group?: CometChat.Group, + user?: CometChat.User; + group?: CometChat.Group; }) => { return ( @@ -506,12 +531,64 @@ return ( ); ``` - + + + + +--- - +## Styling -**Example** +Using Style you can customize the look and feel of the component in your app. These parameters typically control elements such as the color, size, shape, and fonts used within the component. - + + +### Visibility Props + +| Property | Description | Code | +| --- | --- | --- | +| `user` | User object for 1-on-1 conversation | `user={chatUser}` | +| `group` | Group object for group conversation | `group={chatGroup}` | +| `disableTypingEvents` | Disable/enable typing events | `disableTypingEvents={true}` | +| `disableSoundForOutgoingMessages` | Toggle sound for outgoing messages | `disableSoundForOutgoingMessages={true}` | +| `initialComposertext` | Set predefined text | `initialComposertext="Your custom text"` | +| `customSoundForOutgoingMessage` | Custom sound for outgoing messages | `customSoundForOutgoingMessage="your-sound"` | +| `hideVoiceRecordingButton` | Hide voice recording option | `hideVoiceRecordingButton={true}` | +| `hideCameraOption` | Hide camera option from attachments | `hideCameraOption={true}` | +| `hideImageAttachmentOption` | Hide image attachment option | `hideImageAttachmentOption={true}` | +| `hideVideoAttachmentOption` | Hide video attachment option | `hideVideoAttachmentOption={true}` | +| `hideAudioAttachmentOption` | Hide audio attachment option | `hideAudioAttachmentOption={true}` | +| `hideFileAttachmentOption` | Hide file attachment option | `hideFileAttachmentOption={true}` | +| `hidePollsAttachmentOption` | Hide polls attachment option | `hidePollsAttachmentOption={true}` | +| `hideCollaborativeDocumentOption` | Hide collaborative document option | `hideCollaborativeDocumentOption={true}` | +| `hideCollaborativeWhiteboardOption` | Hide collaborative whiteboard option | `hideCollaborativeWhiteboardOption={true}` | +| `hideAttachmentButton` | Hide attachment button | `hideAttachmentButton={true}` | +| `hideStickersButton` | Hide stickers button | `hideStickersButton={true}` | +| `hideSendButton` | Hide send button | `hideSendButton={true}` | +| `hideAuxiliaryButtons` | Hide auxiliary buttons | `hideAuxiliaryButtons={true}` | +| `disableMentions` | Disable mentions functionality | `disableMentions={true}` | +| `disableMentionAll` | Disable @all mention | `disableMentionAll={true}` | +| `mentionAllLabel` | Custom label for @all mention | `mentionAllLabel="everyone"` | +| `imageQuality` | Image quality for camera (1-100) | `imageQuality={50}` | +| `auxiliaryButtonsAlignment` | Alignment of auxiliary buttons | `auxiliaryButtonsAlignment="right"` | + +--- + +## Next Steps + + + + Display the list of messages in a conversation + + + Display user or group details in the chat toolbar + + + Complete messaging interface with header, list, and composer + + + Customize the appearance of UI Kit components + + diff --git a/ui-kit/react-native/message-header.mdx b/ui-kit/react-native/message-header.mdx index ad911688f..3a8538e6c 100644 --- a/ui-kit/react-native/message-header.mdx +++ b/ui-kit/react-native/message-header.mdx @@ -1,442 +1,507 @@ --- title: "Message Header" +description: "Display user or group details in the chat toolbar with CometChatMessageHeader component in React Native UI Kit, including typing indicators and navigation." --- -## Overview + +```json +{ + "component": "CometChatMessageHeader", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatMessageHeader } from \"@cometchat/chat-uikit-react-native\";", + "description": "Displays user or group details in the chat toolbar with typing indicators and navigation controls.", + "props": { + "data": { + "user": { + "type": "CometChat.User", + "note": "User object for one-on-one chat header" + }, + "group": { + "type": "CometChat.Group", + "note": "Group object for group chat header" + } + }, + "callbacks": { + "onBack": "() => void", + "onError": "(error: CometChat.CometChatException) => void", + "onNewChatButtonClick": "() => void", + "onChatHistoryButtonClick": "() => void" + }, + "visibility": { + "showBackButton": { "type": "boolean", "default": true }, + "hideVoiceCallButton": { "type": "boolean", "default": false }, + "hideVideoCallButton": { "type": "boolean", "default": false }, + "usersStatusVisibility": { "type": "boolean", "default": true }, + "hideNewChatButton": { "type": "boolean", "default": true }, + "hideChatHistoryButton": { "type": "boolean", "default": true } + }, + "viewSlots": { + "ItemView": "({ user, group }) => JSX.Element", + "LeadingView": "({ user, group }) => JSX.Element", + "TitleView": "({ user, group }) => JSX.Element", + "SubtitleView": "({ user, group }) => JSX.Element", + "TrailingView": "({ user, group }) => JSX.Element", + "AuxiliaryButtonView": "({ user, group }) => JSX.Element" + }, + "options": { + "options": "({ user, group }) => MenuItemInterface[]" + } + }, + "compositionExample": { + "description": "Header component for message view", + "components": [ + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "Displays user/group info at top of chat, handles back navigation and call buttons" + } +} +``` + + +## Where It Fits -`MessageHeader` is a [Component](/ui-kit/react-native/components-overview#components) that showcases the [User](/sdk/react-native/users-overview) or [Group](/sdk/react-native/groups-overview) details in the toolbar. Furthermore, it also presents a typing indicator and a back navigation button for ease of use. +`CometChatMessageHeader` is a [Component](/ui-kit/react-native/components-overview#components) that showcases the [User](/sdk/react-native/user-management) or [Group](/sdk/react-native/retrieve-groups) details in the toolbar. It presents a typing indicator and a back navigation button for ease of use. -*** - -## Usage - -### Integration +--- -You can add `CometChatMessageHeader` component directly into your component file. +## Minimal Render - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; -//code -return ; -``` - - - +function MessageHeaderDemo() { + return ; +} +``` -### Actions +--- -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +## Actions and Events -The `MessageHeader` component does not have any exposed actions. +### Callback Props -##### onError +#### onError -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Users component. +Fires on internal errors (network failure, auth issue, SDK exception). - - -```tsx -import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; -//code -return ( - { - //handle error - }} - /> -); +```tsx lines +onError?: (error: CometChat.CometChatException) => void ``` - - - - -##### onBack - -`onBack` is triggered when you press the back button in the app bar. It has a predefined behavior; when clicked, it navigates to the previous activity. However, you can override this action using the following code snippet. - - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; -//code -return ( - { - //handle back - }} - /> -); -``` - - - - +import { CometChat } from "@cometchat/chat-sdk-react-native"; -*** +function MessageHeaderWithError() { + return ( + { + console.error("MessageHeader error:", error); + }} + /> + ); +} +``` -*** +#### onBack -##### onNewChatButtonClick +Fires when the back button in the app bar is pressed. Requires `showBackButton={true}`. -`onNewChatButtonClick` is triggered when you press the new chat button in the app bar (only applies to @agentic users). This callback allows you to handle starting a new conversation with the AI assistant. +```tsx lines +onBack?: () => void +``` - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; -//code -return ( - { - // Handle new chat button click - console.log('Starting new AI chat'); - }} - /> -); -``` - - -*** +function MessageHeaderWithBack() { + return ( + { + console.log("Back pressed"); + }} + /> + ); +} +``` -##### onChatHistoryButtonClick +#### onNewChatButtonClick -`onChatHistoryButtonClick` is triggered when you press the chat history button in the app bar (only applies to @agentic users). This callback allows you to handle opening the AI assistant chat history. +Fires when the new chat button is pressed (only applies to AI Assistant users). Allows handling starting a new conversation with the AI assistant. - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; -//code -return ( - { - // Handle chat history button click - console.log('Opening AI chat history'); - }} - /> -); -``` - - -*** +function MessageHeaderWithNewChat() { + return ( + { + console.log("Starting new AI chat"); + }} + /> + ); +} +``` -### Filters +#### onChatHistoryButtonClick -**Filters** allow you to customize the data displayed in a list within a `Component`. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using `RequestBuilders` of Chat SDK. +Fires when the chat history button is pressed (only applies to AI Assistant users). Allows handling opening the AI assistant chat history. -The `MessageHeader` component does not have any exposed filters. +```tsx lines +import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; -### Events +function MessageHeaderWithHistory() { + return ( + { + console.log("Opening AI chat history"); + }} + /> + ); +} +``` -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +--- -The `MessageHeader` component does not produce any events. +## Custom View Slots -## Customization +Each slot replaces a section of the default UI. Slots that accept parameters receive the user or group object for customization. -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +| Slot | Signature | Replaces | +| --- | --- | --- | +| `ItemView` | `({ user, group }) => JSX.Element` | Entire header layout | +| `LeadingView` | `({ user, group }) => JSX.Element` | Avatar / left section | +| `TitleView` | `({ user, group }) => JSX.Element` | Name / title text | +| `SubtitleView` | `({ user, group }) => JSX.Element` | Status / subtitle text | +| `TrailingView` | `({ user, group }) => JSX.Element` | Right section next to call buttons | +| `AuxiliaryButtonView` | `({ user, group }) => JSX.Element` | Replaces default call buttons | -### Style +### TitleView -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Custom view for the name / title text. - - - +```tsx lines +TitleView?: ({ user, group }) => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; -//code -return ( - -); +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { Text } from "react-native"; + +function TitleViewDemo() { + const getTitleView = ({ + user, + group, + }: { + user?: CometChat.User; + group?: CometChat.Group; + }) => { + const name = user ? user.getName() : group?.getName(); + return ( + + {name} + + ); + }; + + return ; +} ``` - - - - -*** - -To know more such attributes, visit the [attributes file](https://github.com/cometchat/cometchat-uikit-android/blob/v5/chatuikit/src/main/res/values/attr_cometchat_message_header.xml). - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Following is a list of customizations along with their corresponding code snippets: +### AuxiliaryButtonView -| Property | Description | Code | -| ------------------------- | ------------------------------------------------------------------------ | ------------------------------ | -| **user** | Used to pass user object of which header specific details will be shown | `user={chatUser}` | -| **group** | Used to pass group object of which header specific details will be shown | `group={chatGroup}` | -| **showBackButton** | Used to toggle back button visibility | `showBackButton={true}` | -| **hideVoiceCallButton** | Used to toggle voice call button visibility | `hideVoiceCallButton={true}` | -| **hideVideoCallButton** | Used to toggle video call button visibility | `hideVideoCallButton={true}` | -| **usersStatusVisibility** | Used to toggle user status visibility | `usersStatusVisibility={true}` | -| **hideNewChatButton** | Used to toggle the visibility of new chat button in case of chats with AI Assistants | `hideNewChatButton={true}` | -| **hideChatHistoryButton** | Used to toggle the visibility of chat history button in case of chats with AI Assistants | `hideChatHistoryButton={true}` | +Custom buttons that replace the default call buttons. -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +```tsx lines +AuxiliaryButtonView?: ({ user, group }) => JSX.Element +``` -#### AuxiliaryButtonView +```tsx lines +import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { TouchableOpacity, Text } from "react-native"; + +function AuxiliaryButtonDemo() { + const getAuxiliaryView = ({ + user, + group, + }: { + user?: CometChat.User; + group?: CometChat.Group; + }) => { + return ( + console.log("Custom action")}> + Custom Button + + ); + }; + + return ( + + ); +} +``` -Allows adding custom buttons that replace the default call buttons. +### ItemView -Use Cases: +Custom view for the entire header layout. -* Add a Call button (📞) for quick voice/video calls. -* Include a Block/Report button for moderation. -* Implement a Pin Chat feature. +```tsx lines +ItemView?: ({ user, group }) => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - { - return ( - { - //do something - }} - > - Custom Button - - ); - }} - /> -); +import { View, Text } from "react-native"; + +function ItemViewDemo() { + const getItemView = ({ + user, + group, + }: { + user?: CometChat.User; + group?: CometChat.Group; + }) => { + const name = user ? user.getName() : group?.getName(); + return ( + + {name} + + ); + }; + + return ; +} ``` - +### SubtitleView - +Custom view for the subtitle / status text. -*** - -#### ItemView - -Enables replacing the entire default header with a fully customized ListItem layout. - -Use Cases: +```tsx lines +SubtitleView?: ({ user, group }) => JSX.Element +``` -* Create a completely unique message header style. -* Include additional user details like bio, location, or last seen status. + + + - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getItemView = ({ - user, - group, -}: { - user?: CometChat.User; - group?: CometChat.Group; -}) => { - //your custom item view - //return jsx; -}; -return ( - -); +import { Text } from "react-native"; + +function SubtitleViewDemo() { + const getSubtitleView = ({ + user, + group, + }: { + user?: CometChat.User; + group?: CometChat.Group; + }) => { + if (user) { + return Online; + } + return {group?.getMembersCount()} members; + }; + + return ; +} ``` - - - - -*** +### LeadingView -#### SubtitleView +Custom view for the avatar / left section. -Allows customizing the subtitle view, usually used for status messages or additional details. - -Use Cases: - -* Show the user's last seen or online status. -* Display a custom typing indicator. -* Show a custom role or tagline ("Customer Support", "Verified Seller"). +```tsx lines +LeadingView?: ({ user, group }) => JSX.Element +``` - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getSubtitleView = ({ - user, - group, -}: { - user?: CometChat.User; - group?: CometChat.Group; -}) => { - //your custom Subtitle view - //return jsx; -}; -return ( - -); +import { View, Text } from "react-native"; + +function LeadingViewDemo() { + const getLeadingView = ({ + user, + group, + }: { + user?: CometChat.User; + group?: CometChat.Group; + }) => { + const name = user ? user.getName() : group?.getName(); + return ( + + + {name?.charAt(0)} + + + ); + }; + + return ; +} ``` - +### TrailingView - +Custom view for the right section next to call buttons. -**Example** +```tsx lines +TrailingView?: ({ user, group }) => JSX.Element +``` - + -*** - -#### LeadingView - -Defines a custom leading view, typically used for the receiver's profile picture or avatar. - -Use Cases: - -* Display a circular profile picture with a status indicator. -* Add a custom badge for special roles (Admin, Verified ✅). - - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getLeadingView = ({ - user, - group, -}: { - user?: CometChat.User; - group?: CometChat.Group; -}) => { - //your custom Leading view - //return jsx; -}; -return ( - -); +import { TouchableOpacity, Text } from "react-native"; + +function TrailingViewDemo() { + const getTrailingView = ({ + user, + group, + }: { + user?: CometChat.User; + group?: CometChat.Group; + }) => { + return ( + console.log("Menu pressed")}> + + + ); + }; + + return ; +} ``` - +--- - +## Styling -**Example** +Using Style you can customize the look and feel of the component in your app. Pass a styling object as a prop to the `CometChatMessageHeader` component. - + -*** +```tsx lines +import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; + +function StylingDemo() { + return ( + + ); +} +``` + +### Visibility Props -#### TrailingView +| Property | Description | Code | +| --- | --- | --- | +| `showBackButton` | Toggle visibility of the back button in the app bar | `showBackButton?: boolean` | +| `hideVoiceCallButton` | Toggle visibility of the voice call button | `hideVoiceCallButton?: boolean` | +| `hideVideoCallButton` | Toggle visibility of the video call button | `hideVideoCallButton?: boolean` | +| `usersStatusVisibility` | Toggle user status visibility | `usersStatusVisibility?: boolean` | +| `hideNewChatButton` | Toggle visibility of new chat button for AI Assistants | `hideNewChatButton?: boolean` | +| `hideChatHistoryButton` | Toggle visibility of chat history button for AI Assistants | `hideChatHistoryButton?: boolean` | -Enables customization of the trailing view which gets added next to the call buttons. +### options -Use Cases: +Custom menu items for the header options menu. -* Add an options menu (⋮) for more actions. -* Display a mute/unmute toggle. -* Show a connection strength indicator for calls. +```tsx lines +options?: ({ user, group }) => MenuItemInterface[] +``` - - -```tsx +```tsx lines import { CometChatMessageHeader } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTrailingView = ({ - user, - group, -}: { - user?: CometChat.User; - group?: CometChat.Group; -}) => { - //your custom Trailing view - //return jsx; -}; -return ( - -); -``` - +function OptionsDemo() { + const getOptions = ({ + user, + group, + }: { + user?: CometChat.User; + group?: CometChat.Group; + }) => { + return [ + { + text: "View Profile", + onPress: () => { /* view profile logic */ }, + }, + { + text: "Block User", + onPress: () => { /* block logic */ }, + }, + ]; + }; - + return ; +} +``` -**Example** +--- - - - +## Next Steps + + + + Display the list of messages in a conversation + + + Compose and send messages in a chat + + + Complete messaging interface with header, list, and composer + + + Customize the appearance of UI Kit components + + diff --git a/ui-kit/react-native/message-list.mdx b/ui-kit/react-native/message-list.mdx index 5c878cf57..2a3e52183 100644 --- a/ui-kit/react-native/message-list.mdx +++ b/ui-kit/react-native/message-list.mdx @@ -1,1181 +1,1356 @@ --- title: "Message List" +description: "Scrollable list of sent and received messages with text, media, reactions, read receipts, threaded replies, and AI features." --- + +```json +{ + "component": "CometChatMessageList", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatMessageList } from \"@cometchat/chat-uikit-react-native\";", + "description": "Scrollable list of sent and received messages with text, media, reactions, read receipts, threaded replies, and AI features.", + "primaryOutput": { + "prop": "onThreadRepliesPress", + "type": "(messageObject: CometChat.BaseMessage, messageBubbleView: () => JSX.Element | null) => void" + }, + "props": { + "data": { + "user": { "type": "CometChat.User", "default": "undefined", "note": "User object for 1-on-1 conversation" }, + "group": { "type": "CometChat.Group", "default": "undefined", "note": "Group object for group conversation" }, + "messageRequestBuilder": { "type": "CometChat.MessagesRequestBuilder", "default": "SDK default", "note": "UID/GUID/types/categories are always overridden internally" }, + "templates": { "type": "CometChatMessageTemplate[]", "default": "SDK defaults", "note": "Custom message bubble templates" }, + "addTemplates": { "type": "CometChatMessageTemplate[]", "default": "[]", "note": "Additional message templates to append to defaults" }, + "parentMessageId": { "type": "number", "default": "undefined", "note": "For threaded message view" }, + "goToMessageId": { "type": "string", "default": "undefined", "note": "Message ID to navigate to and highlight" }, + "searchKeyword": { "type": "string", "default": "undefined", "note": "Keyword to highlight in message text" } + }, + "callbacks": { + "onThreadRepliesPress": "(messageObject: CometChat.BaseMessage, messageBubbleView: () => JSX.Element | null) => void", + "onError": "(error: CometChat.CometChatException) => void", + "onReactionPress": "(reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void", + "onReactionLongPress": "(reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void", + "onReactionListItemPress": "(reaction: CometChat.Reaction, messageObject: CometChat.BaseMessage) => void", + "onAddReactionPress": "() => void", + "onSuggestedMessageClick": "(suggestion: string) => void", + "onLoad": "(messageList: CometChat.BaseMessage[]) => void", + "onEmpty": "() => void" + }, + "visibility": { + "receiptsVisibility": { "type": "boolean", "default": true }, + "avatarVisibility": { "type": "boolean", "default": true }, + "hideError": { "type": "boolean", "default": false }, + "hideTimestamp": { "type": "boolean", "default": false }, + "hideReplyOption": { "type": "boolean", "default": false }, + "hideReplyInThreadOption": { "type": "boolean", "default": false }, + "hideShareMessageOption": { "type": "boolean", "default": false }, + "hideEditMessageOption": { "type": "boolean", "default": false }, + "hideDeleteMessageOption": { "type": "boolean", "default": false }, + "hideTranslateMessageOption": { "type": "boolean", "default": false }, + "hideReactionOption": { "type": "boolean", "default": false }, + "hideMessagePrivatelyOption": { "type": "boolean", "default": false }, + "hideCopyMessageOption": { "type": "boolean", "default": false }, + "hideMessageInfoOption": { "type": "boolean", "default": false }, + "hideGroupActionMessages": { "type": "boolean", "default": false }, + "hideModerationStatus": { "type": "boolean", "default": false }, + "hideSuggestedMessages": { "type": "boolean", "default": false }, + "showMarkAsUnreadOption": { "type": "boolean", "default": false }, + "hideFlagMessageOption": { "type": "boolean", "default": false }, + "hideFlagRemarkField": { "type": "boolean", "default": false } + }, + "behavior": { + "alignment": { "type": "MessageListAlignmentType", "values": ["leftAligned", "standard"], "default": "standard" }, + "scrollToBottomOnNewMessage": { "type": "boolean", "default": false }, + "startFromUnreadMessages": { "type": "boolean", "default": false }, + "streamingSpeed": { "type": "number", "default": "undefined", "note": "AI response streaming speed in ms" } + }, + "sound": { + "disableSoundForMessages": { "type": "boolean", "default": false }, + "customSoundForMessages": { "type": "audio source", "default": "built-in" } + }, + "ai": { + "suggestedMessages": { "type": "string[]", "note": "Predefined prompts for AI assistant chats" }, + "aiAssistantTools": { "type": "CometChatAIAssistantTools", "note": "Tool actions for AI assistant" }, + "quickReactionList": { "type": "string[]", "default": "predefined reactions" }, + "streamingSpeed": { "type": "number", "default": "undefined", "note": "AI response streaming speed in ms" } + }, + "viewSlots": { + "HeaderView": "({ user, group, id }) => JSX.Element", + "FooterView": "({ user, group, id }) => JSX.Element", + "LoadingView": "() => JSX.Element", + "EmptyView": "() => JSX.Element", + "ErrorView": "() => JSX.Element", + "NewMessageIndicatorView": "() => JSX.Element", + "emptyChatGreetingView": "JSX.Element", + "emptyChatIntroMessageView": "JSX.Element", + "emptyChatImageView": "JSX.Element" + }, + "newMessageIndicator": { + "newMessageIndicatorStyle": { "type": "NewMessageIndicatorStyle", "default": "built-in" }, + "newMessageIndicatorText": { "type": "string", "default": "built-in" } + }, + "formatting": { + "textFormatters": { "type": "CometChatTextFormatter[]", "default": "default formatters from data source" }, + "datePattern": "(message: CometChat.BaseMessage) => string", + "dateSeperatorPattern": "(date: number) => string" + } + }, + "events": [ + { "name": "openChat", "payload": "{ user, group }", "description": "User opens a chat" }, + { "name": "ccMessageEdited", "payload": "{ message }", "description": "Message edited by logged-in user" }, + { "name": "ccMessageDeleted", "payload": "{ message }", "description": "Message deleted by logged-in user" }, + { "name": "ccActiveChatChanged", "payload": "chat details", "description": "User navigates to a different chat" }, + { "name": "ccMessageRead", "payload": "{ message }", "description": "Message read by logged-in user" }, + { "name": "ccMessageDelivered", "payload": "{ message }", "description": "Messages marked as delivered" } + ], + "sdkListeners": [ + "onTextMessageReceived", "onMediaMessageReceived", "onCustomMessageReceived", + "onMessageEdited", "onMessageDeleted", "onTypingStarted", "onTypingEnded", + "onMessagesDelivered", "onMessagesRead" + ], + "compositionExample": { + "description": "Message list wired with header and composer for complete chat view", + "components": ["CometChatMessageHeader", "CometChatMessageList", "CometChatMessageComposer"], + "flow": "Pass user or group prop to all three components for a complete messaging interface" + }, + "types": { + "MessageListAlignmentType": { "leftAligned": "All messages aligned to left", "standard": "Sent messages right, received messages left" } + } +} +``` + -## Overview +## Where It Fits -`MessageList` is a [Composite Component](/ui-kit/react-native/components-overview#components) that displays a list of messages and effectively manages real-time operations. It includes various types of messages such as Text Messages, Media Messages, Stickers, and more. +`CometChatMessageList` renders a scrollable, real-time message feed for a user or group conversation. Wire it alongside `CometChatMessageHeader` and `CometChatMessageComposer` to build a standard chat view. + +```tsx lines +import { useState, useEffect } from "react"; +import { View, StyleSheet } from "react-native"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatThemeProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function ChatView() { + const [chatUser, setChatUser] = useState(); + + useEffect(() => { + CometChat.getUser("uid").then((user) => setChatUser(user)); + }, []); + + return chatUser ? ( + + + + + + + + + + + + ) : null; +} -`MessageList` is primarily a list of the base component [MessageBubble](/ui-kit/react-native/message-bubble-styling#message-bubbles). The MessageBubble Component is utilized to create different types of chat bubbles depending on the message type. +const styles = StyleSheet.create({ + container: { flex: 1 }, +}); +``` -## Usage - -### Integration +--- -The following code snippet illustrates how you can directly incorporate the `CometChatMessageList` component into your app. +## Minimal Render - - -```tsx +```tsx lines import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -//code -return ; -``` - +function MessageListDemo() { + return ; +} - +export default MessageListDemo; +``` - Simply adding the `CometChatMessageList` component to the layout will result in an error. To fetch messages, you need to supplement it with `user` or `group` prop. - -*** - -### Actions - -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +--- -##### 1. onThreadRepliesPress +## Filtering Messages -`onThreadRepliesPress` is triggered when you press on the threaded message bubble. The `onThreadRepliesPress` action doesn't have a predefined behavior. You can override this action using the following code snippet. +Pass a `CometChat.MessagesRequestBuilder` to `messageRequestBuilder`. The `UID`/`GUID` parameters are always overridden internally based on the `user`/`group` prop. - - -```tsx +```tsx lines import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const threadRepliesCallback = ( - msg: CometChat.BaseMessage, - messageBubbleView: () => JSX.Element | null -) => { - //handle thread -}; - -return ( - -); + +function FilteredMessageList() { + return ( + + ); +} ``` - + +The following parameters in messageRequestBuilder will always be altered inside the message list: +1. UID +2. GUID +3. types +4. categories + + +Refer to [MessagesRequestBuilder](/sdk/react-native/additional-message-filtering) for the full builder API. + +--- + +## Actions and Events - +### Callback Props -##### 2. onError +#### onThreadRepliesPress -This action doesn't change the behavior of the component but rather listens for any errors that occur in the MessageList component. +Fires when you press on the threaded message bubble. - - -```tsx +```tsx lines import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const errorHandler = (e: CometChat.CometChatException) => { - //handle error -}; - -return ( - -); + +function MessageListWithThreads() { + const handleThreadReplies = ( + msg: CometChat.BaseMessage, + messageBubbleView: () => JSX.Element | null + ) => { + console.log("Thread replies pressed:", msg.getId()); + }; + + return ( + + ); +} ``` - +#### onError - +Fires on internal errors (network failure, auth issue, SDK exception). -*** +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function MessageListWithErrorHandler() { + return ( + { + console.error("MessageList error:", error); + }} + /> + ); +} +``` -##### onReactionLongPress +#### onReactionPress -Function triggered when a user long presses on a reaction pill, allowing developers to override the default behavior. +Fires when a reaction on a message bubble is clicked. - - -```tsx +```tsx lines import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const onReactionLongPress = ( - reaction: CometChat.ReactionCount, - messageObject: CometChat.BaseMessage -) => {}; - -return ( - -); -``` - +function MessageListWithReactions() { + const handleReactionPress = ( + reaction: CometChat.ReactionCount, + messageObject: CometChat.BaseMessage + ) => { + console.log("Reaction pressed:", reaction, messageObject.getId()); + }; - + return ( + + ); +} +``` -##### onAddReactionPress +#### onLoad -Function triggered when a user clicks on the 'Add More Reactions' button, allowing developers to handle this action. +Fires when messages are successfully fetched and loaded. - - -```tsx +```tsx lines import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const onAddReactionPress = () => {}; - -return ( - -); + +function MessageListWithLoadHandler() { + const handleLoad = (messageList: CometChat.BaseMessage[]) => { + console.log("Messages loaded:", messageList.length); + }; + + return ; +} ``` - +### Global UI Events - +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Subscribe in a `useEffect` and unsubscribe on cleanup. -##### onReactionPress +| Event | Fires when | Payload | +| --- | --- | --- | +| `openChat` | User opens a user or group chat | `{ user, group }` | +| `ccMessageEdited` | Message edited by logged-in user | `{ message }` | +| `ccMessageDeleted` | Message deleted by logged-in user | `{ message }` | +| `ccActiveChatChanged` | User navigates to a different chat | `chat details` | +| `ccMessageRead` | Message read by logged-in user | `{ message }` | +| `ccMessageDelivered` | Messages marked as delivered | `{ message }` | -Function triggered when a reaction is clicked, enabling developers to customize reaction interactions. +```tsx lines +import { useEffect } from "react"; +import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const onReactionPress = ( - reaction: CometChat.ReactionCount, - messageObject: CometChat.BaseMessage -) => {}; - -return ( - -); +function useMessageListEvents() { + useEffect(() => { + const uiListenerId = "UI_LISTENER_" + Date.now(); + const messageListenerId = "MESSAGE_LISTENER_" + Date.now(); + + CometChatUIEventHandler.addUIListener(uiListenerId, { + openChat: ({ user, group }) => { + console.log("Chat opened:", user || group); + }, + }); + + CometChatUIEventHandler.addMessageListener(messageListenerId, { + ccMessageEdited: ({ message }) => { + console.log("Message edited:", message.getId()); + }, + ccMessageDeleted: ({ message }) => { + console.log("Message deleted:", message.getId()); + }, + }); + + return () => { + CometChatUIEventHandler.removeUIListener(uiListenerId); + CometChatUIEventHandler.removeMessageListener(messageListenerId); + }; + }, []); +} ``` - +### SDK Events (Real-Time, Automatic) + +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. + +| SDK Listener | Internal behavior | +| --- | --- | +| `onTextMessageReceived` / `onMediaMessageReceived` / `onCustomMessageReceived` | Appends new message to list | +| `onMessageEdited` / `onMessageDeleted` | Updates/removes message in list | +| `onTypingStarted` / `onTypingEnded` | Shows/hides typing indicator | +| `onMessagesDelivered` / `onMessagesRead` | Updates receipt ticks | + +--- + +## Custom View Slots + +Each slot replaces a section of the default UI. - +| Slot | Signature | Replaces | +| --- | --- | --- | +| `HeaderView` | `({ user, group, id }) => JSX.Element` | Area above the message list | +| `FooterView` | `({ user, group, id }) => JSX.Element` | Area below the message list | +| `LoadingView` | `() => JSX.Element` | Loading state | +| `EmptyView` | `() => JSX.Element` | Empty state | +| `ErrorView` | `() => JSX.Element` | Error state | +| `NewMessageIndicatorView` | `() => JSX.Element` | New messages indicator | +| `templates` | `CometChatMessageTemplate[]` | Message bubble rendering | +| `textFormatters` | `CometChatTextFormatter[]` | Text formatting in messages | -##### onReactionListItemPress +### HeaderView -Function triggered when a reaction list item is clicked, allowing developers to override its behavior in CometChatReactionsList. +Custom view above the message list. - - -```tsx + + + + +```tsx lines import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const onReactionListItemPress = ( - reaction: CometChat.Reaction, - messageObject: CometChat.BaseMessage -) => {}; - -return ( - -); +import { View, Text, TouchableOpacity } from "react-native"; + +function MessageListWithHeader() { + const getHeaderView = ({ + user, + group, + id, + }: { + user?: CometChat.User; + group?: CometChat.Group; + id?: { uid?: string; guid?: string; parentMessageId?: string }; + }) => { + return ( + + + Notes + + + Pinned + + + ); + }; + + return ; +} ``` - +### FooterView - +Custom view below the message list. + + + + -### Filters +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text, TouchableOpacity } from "react-native"; + +function MessageListWithFooter() { + const getFooterView = ({ + user, + group, + id, + }: { + user?: CometChat.User; + group?: CometChat.Group; + id?: { uid?: string; guid?: string; parentMessageId?: string }; + }) => { + return ( + + + Ice Breakers + + + ); + }; -You can adjust the `MessagesRequestBuilder` in the MessageList Component to customize your message list. Numerous options are available to alter the builder to meet your specific needs. For additional details on `MessagesRequestBuilder`, please visit [MessagesRequestBuilder](/sdk/react-native/additional-message-filtering). + return ; +} +``` -In the example below, we are applying a filter to the messages based on a search substring and for a specific user. This means that only messages that contain the search term and are associated with the specified user will be displayed +### templates - - -```tsx +Custom message bubble templates via CometChatMessageTemplate. -import { CometChat } from '@cometchat/chat-sdk-react-native'; -import { CometChatMessageList } from '@cometchat/chat-uikit-react-native'; +```tsx lines +import { CometChatMessageList, ChatConfigurator, CometChatMessageTemplate } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { Text } from "react-native"; + +function MessageListCustomTemplates() { + const getTemplates = () => { + let templates: CometChatMessageTemplate[] = ChatConfigurator.getDataSource().getAllMessageTemplates(theme); + templates.map((data) => { + if (data.type === "text") { + data.ContentView = (messageObject: CometChat.BaseMessage) => { + const textMessage = messageObject as CometChat.TextMessage; + return ( + + {textMessage.getText()} + + ); + }; + } + }); + return templates; + }; -function App(): React.JSX.Element { - const [chatUser, setChatUser] = React.useState(); + return ; +} +``` - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }) - }, []); +### dateSeperatorPattern - const messageRequestBuilder = new CometChat.MessagesRequestBuilder().setLimit(5); +Custom format for displaying sticky date separators. - return ( - <> - { chatUser && - } - - ); +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; + +function MessageListCustomDateSeparator() { + const customDateSeparatorPattern = (date: number) => { + const timeStampInSeconds = new Date(date * 1000); + const day = String(timeStampInSeconds.getUTCDate()).padStart(2, "0"); + const month = String(timeStampInSeconds.getUTCMonth() + 1).padStart(2, "0"); + const year = timeStampInSeconds.getUTCFullYear(); + return `${day}/${month}/${year}`; + }; + + return ( + + ); } ``` - +### datePattern - +Custom format for message timestamps. - +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -The following parameters in messageRequestBuilder will always be altered inside the message list +function MessageListCustomDatePattern() { + const generateDateString = (message: CometChat.BaseMessage) => { + const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + const timeStamp = message.getSentAt(); + if (timeStamp) { + const date = new Date(timeStamp * 1000); + const day = days[date.getUTCDay()]; + const hours = date.getUTCHours(); + const minutes = String(date.getUTCMinutes()).padStart(2, "0"); + return `${day}, ${hours}:${minutes}`; + } + return "---, --:--"; + }; -1. UID -2. GUID -3. types -4. categories + return ( + + ); +} +``` - +### textFormatters -*** +Custom text formatters for message content. -### Events + + + + +```tsx lines +import { + CometChatMessageList, + CometChatTextFormatter, + CometChatMentionsFormatter, +} from "@cometchat/chat-uikit-react-native"; -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +function MessageListWithFormatters() { + const getTextFormatters = () => { + const textFormatters: CometChatTextFormatter[] = []; + const mentionsFormatter = new CometChatMentionsFormatter(); + mentionsFormatter.setMentionsStyle({ + textStyle: { color: "#D6409F" }, + selfTextStyle: { color: "#30A46C" }, + }); + textFormatters.push(mentionsFormatter); + return textFormatters; + }; -The list of events emitted by the Message List component is as follows. + return ( + + ); +} +``` -| Event | Description | -| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------- | -| **openChat** | this event alerts the listeners if the logged-in user has opened a user or a group chat | -| **ccMessageEdited** | Triggers whenever a loggedIn user edits any message from the list of messages. It will have two states such as: inProgress & sent | -| **ccMessageDeleted** | Triggers whenever a loggedIn user deletes any message from the list of messages | -| **ccActiveChatChanged** | This event is triggered when the user navigates to a particular chat window. | -| **ccMessageRead** | Triggers whenever a loggedIn user reads any message. | -| **ccMessageDelivered** | Triggers whenever messages are marked as delivered for the loggedIn user | +See [CometChatMentionsFormatter](/ui-kit/react-native/mentions-formatter-guide) for mention formatting. -Adding `CometChatMessageEvents` Listener's +--- - - -```js -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +## Common Patterns -CometChatUIEventHandler.addUIListener("UI_LISTENER_ID", { - openChat: ({ user, group }) => { - //code - }, -}); +### Threaded message list -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - ccMessageEdited: ({ message }) => { - //code - }, -}); +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - ccMessageDeleted: ({ message }) => { - //code - }, -}); +function ThreadedMessageList() { + return ( + + ); +} +``` -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - ccMessageDelivered: ({ message }) => { - //code - }, -}); +### Hide all chrome — minimal list -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - ccMessageRead: ({ message }) => { - //code - }, -}); +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.addMessageListener("MESSAGE_LISTENER_ID", { - addMessageListener: ({ message, user, group, theme, parentMessageId }) => { - //code - }, -}); +function MinimalMessageList() { + return ( + + ); +} ``` - +### Left-aligned messages - +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -*** +function LeftAlignedList() { + return ( + + ); +} +``` -Removing Listeners +### AI conversation starters - - -```js -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.removeUIListener("UI_LISTENER_ID"); -CometChatUIEventHandler.removeMessageListener("MESSAGE_LISTENER_ID"); -``` +function AIMessageList() { + const suggestedMessages = [ + "How can I help you today?", + "Tell me more about your issue.", + "What would you like to achieve?", + ]; - + return ( + console.log("Clicked:", suggestion)} + /> + ); +} +``` - +### Navigate to specific message -*** +```tsx lines +import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -## Customization +function NavigateToMessage() { + return ( + + ); +} +``` -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +--- -### Style +## Styling -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +The component uses the theme system from `CometChatThemeProvider`. Pass a `style` prop to customize the appearance. - - -```tsx +```tsx lines import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code - -return ( - -); + outgoingMessageBubbleStyles: { + containerStyle: { + backgroundColor: "#F76808", + }, + }, + }} + /> + ); +} ``` - +### Style Properties - +| Property | Type | Description | +| --- | --- | --- | +| `containerStyle` | `ViewStyle` | Style for the root container | +| `incomingMessageBubbleStyles` | `object` | Style for incoming message bubbles | +| `outgoingMessageBubbleStyles` | `object` | Style for outgoing message bubbles | +| `dateSeparatorStyle` | `object` | Style for date separators | +| `actionSheetStyle` | `object` | Style for the action sheet | -### Functionality +--- -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. +## Props -Below is a list of customizations along with corresponding code snippets +All props are optional unless noted. Either `user` or `group` is required. - - - +### alignment -| Property | Description | Code | -| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- | -| **user** | Used to pass user object of which header specific details will be shown | `user={chatUser}` | -| **group** | Used to pass group object of which header specific details will be shown | `group={chatGroup}` | -| **alignment** | used to set the alignmet of messages in CometChatMessageList. It can be either **leftAligned** or **standard**. Type: **MessageListAlignmentType** | `alignment={"standard"}` | -| **disableSoundForMessages** | used to enable/disable sound for incoming/outgoing messages , default false | `disableSoundForMessages={true}` | -| **customSoundForMessages** | used to set custom sound for outgoing message | `customSoundForMessages="your custom sound for messages"` | -| **avatarVisibility** | used to toggle visibility for avatar | `avatarVisibility={true}` | -| **scrollToBottomOnNewMessage** | should scroll to bottom on new message? , by default false | `scrollToBottomOnNewMessages={true}` | -| **receiptsVisibility** | Used to control the visibility of read receipts without affecting the functionality of marking messages as read and delivered. | `receiptsVisibility={true}` | -| **hideError** | used to toggle visibility of error state in MessageList | `hideError={true}` | -| **quickReactionList** | The list of quick reactions to be set.This list will replace the predefined set of reactions | `quickReactionList=["👻","😈","🙀","🤡","❤️"];` | -| **hideReplyInThreadOption** | used to toggle visibility of Reply in thread option in MessageList | `hideReplyInThreadOption={true}` | -| **hideShareMessageOption** | used to toggle visibility of share message option in MessageList | `hideShareMessageOption={true}` | -| **hideEditMessageOption** | used to toggle visibility of hide edit message option in MessageList | `hideEditMessageOption={true}` | -| **hideTranslateMessageOption** | used to toggle visibility of translate message option in MessageList | `hideTranslateMessageOption={true}` | -| **hideDeleteMessageOption** | used to toggle visibility of Delete message option in MessageList | `hideDeleteMessageOption={true}` | -| **hideMessagePrivatelyOption** | used to toggle visibility of hide message privately option in MessageList | `hideMessagePrivatelyOption={true}` | -| **hideCopyMessageOption** | used to toggle visibility of hide copy message option in MessageList | `hideCopyMessageOption={true}` | -| **hideMessageInfoOption** | used to toggle visibility of hide message info option in MessageList | `hideMessageInfoOption={true}` | -| **hideGroupActionMessages** | used to toggle visibility of hide group action info option in MessageList | `hideGroupActionMessages={true}` | -| **hideTimestamp** | used to toggle visibility of hide timestamp in MessageList | `hideTimestamp={true}` | -| **startFromUnreadMessages** | When set to true, the chat will load from the first unread message if unread messages exist, otherwise loads from the latest messages. Default is false. | `startFromUnreadMessages={true}` | -| **showMarkAsUnreadOption** | When set to true, shows the "Mark Unread" option in the message actions menu. This option will only appear for received messages, not for the user's own messages. Default is false. | `showMarkAsUnreadOption={true}` | -| **NewMessageIndicatorView** | Custom view component for the "New Messages" indicator. | `NewMessageIndicatorView={MyCustomIndicator}` | -| **newMessageIndicatorStyle** | Custom styles for the "New Messages" indicator. | `newMessageIndicatorStyle={{ backgroundColor: 'red' }}` | -| **newMessageIndicatorText** | Text to display in the "New Messages" indicator. | `newMessageIndicatorText="New Messages"` | - -*** - -### Advance - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -#### Templates - -[CometChatMessageTemplate](/ui-kit/react-native/message-template) is a pre-defined structure for creating message views that can be used as a starting point or blueprint for creating message views often known as message bubbles. For more information, you can refer to [CometChatMessageTemplate](/ui-kit/react-native/message-template). - -You can set message Templates to MessageList by using the following code snippet - - - -```tsx -import { CometChat } from '@cometchat/chat-sdk-react-native'; -import { CometChatMessageList, BorderStyleInterface, AvatarStyleInterface } from '@cometchat/chat-uikit-react-native'; - -function App(): React.JSX.Element { - const [chatUser, setChatUser] = React.useState(); - - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }) - }, []); - - const getTemplates = () => { - let templates : CometChatMessageTemplate[] = ChatConfigurator.getDataSource().getAllMessageTemplates(theme); - templates.map((data) => { - if(data.type == "text") { - data.ContentView = (messageObject: CometChat.BaseMessage, alignment: MessageBubbleAlignmentType) => { - const textMessage : CometChat.TextMessage = (messageObject as CometChat.TextMessage); - return {textMessage.getText()} - } - } - }); - return templates; - }; +Controls message alignment. - return ( - <> - { chatUser && - } - - ); -} -``` +| | | +| --- | --- | +| Type | `"leftAligned" \| "standard"` | +| Default | `"standard"` | - +--- - +### avatarVisibility -#### DateSeperatorPattern +Shows/hides avatars on messages. -Specifies a custom format for displaying sticky date separators in the chat. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -Use Cases: +--- -* Customize date formats to match regional preferences. -* Use relative formats like "Yesterday" instead of full dates. -* Highlight weekend conversations with different styles. +### customSoundForMessages - - -```tsx -import React from "react"; -import { CometChat } from '@cometchat/chat-sdk-react-native'; -import { CometChatMessageList, BorderStyleInterface, AvatarStyleInterface } from '@cometchat/chat-uikit-react-native'; +Custom sound file for incoming message notifications. -function App(): React.JSX.Element { - const [chatUser, setChatUser] = React.useState(); +| | | +| --- | --- | +| Type | `audio source` | +| Default | Built-in sound | - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }) - }, []); +--- - const customDateSeparatorPattern = (date: number) => { - const timeStampInSeconds = new Date(date * 1000); +### datePattern - const day = String(timeStampInSeconds.getUTCDate()).padStart(2, '0'); - const month = String(timeStampInSeconds.getUTCMonth() + 1).padStart(2, '0'); // Months are 0-indexed - const year = timeStampInSeconds.getUTCFullYear(); +Custom function to format message timestamps. - const hours = String(timeStampInSeconds.getUTCHours()).padStart(2, '0'); - const minutes = String(timeStampInSeconds.getUTCMinutes()).padStart(2, '0'); +| | | +| --- | --- | +| Type | `(message: CometChat.BaseMessage) => string` | +| Default | Component default | - return `${day}/${month}/${year}, ${hours}:${minutes}`; - } +--- - return ( - <> - { chatUser && - } - - ); -} -``` +### dateSeperatorPattern - +Custom function to format date separator timestamps. - +| | | +| --- | --- | +| Type | `(date: number) => string` | +| Default | Component default | -*** +--- -#### DatePattern +### disableSoundForMessages -Defines the format in which time appears for each message bubble. +Disables the notification sound for incoming messages. -Use Cases: +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -* Use 12-hour or 24-hour formats based on user preference. -* Display relative time ("Just now", "5 min ago"). -* Add AM/PM indicators for clarity. +--- - - -```tsx -import React from "react"; -import { CometChat } from '@cometchat/chat-sdk-react-native'; -import { CometChatMessageList, BorderStyleInterface, AvatarStyleInterface } from '@cometchat/chat-uikit-react-native'; +### EmptyView -function App(): React.JSX.Element { - const [chatUser, setChatUser] = React.useState(); +Custom component displayed when there are no messages. - React.useEffect(() => { - CometChat.getUser("uid").then((user) => { - setChatUser(user); - }) - }, []); +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in empty state | - const generateDateString = (message: CometChat.BaseMessage) : any => { - const days = [ - 'Sunday', - 'Monday', - 'Tuesday', - 'Wednesday', - 'Thursday', - 'Friday', - 'Saturday', - ]; - const timeStamp = message['sentAt']; - if(timeStamp) { - const timeStampInSeconds = new Date(timeStamp * 1000); - const day = days[timeStampInSeconds.getUTCDay()].substring(0, 3); - const hours = timeStampInSeconds.getUTCHours(); - const minutes = String(timeStampInSeconds.getUTCMinutes()).padStart(2, '0'); +--- - return `${day}, ${hours}:${minutes}`; - } +### ErrorView - return `---, --:--`; - }; +Custom component displayed when an error occurs. - return ( - <> - { chatUser && - } - - ); -} -``` +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in error state | - +--- - +### FooterView -*** +Custom component displayed below the message list. -#### LoadingView +| | | +| --- | --- | +| Type | `({ user, group, id }) => JSX.Element` | +| Default | `undefined` | -Customizes the loading indicator when messages are being fetched. +--- -Use Cases: +### goToMessageId -* Show a spinner or skeleton loader for smooth UX. -* Display a "Fetching messages..." text. +Scrolls to the specified message on initial load. - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code - -const getLoadingView = (): JSX.Element => { - //return jsx; -}; - -return ( - -); -``` +| | | +| --- | --- | +| Type | `string` | +| Default | `undefined` | - +--- - +### group -*** +The group for group conversation messages. -#### EmptyView +| | | +| --- | --- | +| Type | `CometChat.Group` | +| Default | `undefined` | -Defines a custom view to be displayed when no messages are available. +--- -Use Cases: +### HeaderView -* Show a friendly message like "No messages yet. Start the conversation!". +Custom component displayed above the message list. - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code - -const getEmptyView = (): JSX.Element => { - //return jsx; -}; - -return ( - -); -``` +| | | +| --- | --- | +| Type | `({ user, group, id }) => JSX.Element` | +| Default | `undefined` | - +--- - +### hideCopyMessageOption -*** +Hides the copy message option. -#### ErrorView +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Custom error state view displayed when fetching messages fails. +--- -Use Cases: +### hideDeleteMessageOption -* Show a retry button when an error occurs. -* Display a friendly message like "Couldn't load messages. Check your connection. +Hides the delete message option. - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code - -const getErrorView = (): JSX.Element => { - //return jsx; -}; - -return ( - -); -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- - +### hideEditMessageOption +Hides the edit message option. -*** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -#### emptyChatGreetingView +--- -Custom empty state view displayed in case of chats with AI Assistants. +### hideError -Use Cases: +Hides the error state view. -* Show an empty state view for chats with AI Assistants. -* Display a friendly message like "Hey, I am your AI Assistant". +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { View, Text } from "react-native"; +--- -const getAIGreetingView = () => { - return ( - - - Hey, I am your AI Assistant - - - How can I help you today? - - - ); -}; - -return ( - -); -``` - - +### hideFlagMessageOption -*** +Hides the "Report Message" option. -#### suggestedMessages +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Sets the list of suggested messages for AI Assistant chats, allowing you to define which predefined queries or prompts are displayed to users. +--- -Use Cases: +### hideFlagRemarkField -* Display a list of suggested messages for users to interact with the AI Assistant. -* Provide quick prompts or queries to help users start a conversation with the AI. +Hides the remark text area in the flag message dialog. - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -const aiSuggestedMessages = [ - "How can I help you today?", - "Tell me more about your issue.", - "Can you provide more details?", - "What would you like to achieve?" -]; - -const handleSuggestedMessageClick = (suggestion: string) => { - console.log('Suggested message clicked:', suggestion); - // Handle the suggested message click -}; - -return ( - -); -``` - - +--- -*** +### hideGroupActionMessages -#### aiAssistantTools +Hides group action messages (join, leave, kick, etc.). -Sets the available tools for the AI assistant by accepting a `CometChatAIAssistantTools` object that contains tool actions. This allows you to define and manage the tools that the AI assistant can utilize during interactions. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Use Cases: +--- -* Dynamically update UI elements based on tool actions. -* Enable contextual actions based on user interactions with AI tools. +### hideMessageInfoOption - - -```tsx -import { CometChatMessageList, CometChatAIAssistantTools } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; +Hides the message info option. -const aiTools = new CometChatAIAssistantTools({ - getCurrentWeather: (args: any) => { - console.log('Weather tool called with:', args); - // Handle weather tool action - }, - getLocationInfo: (args: any) => { - console.log('Location tool called with:', args); - // Handle location tool action - }, - sendEmail: (args: any) => { - console.log('Email tool called with:', args); - // Handle email tool action - } -}); +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -return ( - -); -``` - - +--- -*** +### hideMessagePrivatelyOption -#### streamingSpeed +Hides the "Message Privately" option. -Sets the streaming speed for AI Assistant responses in milliseconds, allowing you to control how quickly the AI's replies are displayed to the user. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Use Cases: +--- -* Manipulate the speed of AI responses to enhance user experience. +### hideModerationStatus - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; +Hides the moderation status UI. -return ( - -); -``` - - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** +--- -#### hideSuggestedMessages +### hideReactionOption -Flag to hide suggested messages in AI agent empty view (only applies to @agentic users). +Hides the reaction option. -Use Cases: +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -* Hide suggested messages when you want to show a clean empty state. +--- - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; +### hideReplyInThreadOption -return ( - -); -``` - - +Hides the "Reply in Thread" option. -*** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -#### emptyChatIntroMessageView +--- -Custom AI agent intro message view (only applies to @agentic users). +### hideReplyOption -Use Cases: +Hides the reply option. -* Display a custom introduction message for AI assistants. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { View, Text } from "react-native"; +--- -const getAIIntroView = () => { - return ( - - - Welcome! I'm here to assist you with any questions or tasks you might have. - - - ); -}; - -return ( - -); -``` - - +### hideShareMessageOption -*** +Hides the share message option. -#### emptyChatImageView +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -Custom AI agent image/avatar view (only applies to @agentic users). +--- -Use Cases: +### hideSuggestedMessages -* Display a custom avatar or image for AI assistants. +Hides suggested messages in AI view. - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { View, Image } from "react-native"; +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -const getAIImageView = () => { - return ( - - - - ); -}; - -return ( - -); -``` - - +--- -*** +### hideTimestamp -#### TextFormatters +Hides timestamps on messages. -Assigns the list of text formatters. If the provided list is not null, it sets the list. Otherwise, it assigns the default text formatters retrieved from the data source. To configure the existing Mentions look and feel check out [MentionsFormatter Guide](/ui-kit/react-native/mentions-formatter-guide) +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code - -const getTextFomatters = () => { - const textFormatters: CometChatTextFormatter[] = []; - const customMentionsFormatter = new CustomMentionsFormatter(); - textFormatters.push(customMentionsFormatter); - return textFormatters; -}; - -return ( - -); -``` +--- - +### hideTranslateMessageOption - -```ts -import { - CometChatMentionsFormatter, - CometChatTheme, - CometChatUIKit, -} from "@cometchat/chat-uikit-react-native"; +Hides the translate message option. -/** - * Represents the CometChatMentionsFormatter class. - * This class extends the CometChatTextFormatter class and provides methods for handling mentions in text. - * @extends CometChatTextFormatter - */ -export class CustomMentionsFormatter extends CometChatMentionsFormatter { - /** - * Sets the mentions style. - * - * @param {CometChatTheme["mentionsStyle"]} mentionsStyle - The mentions style to be set. - */ - setMentionsStyle(mentionsStyle: CometChatTheme["mentionsStyle"]) { - if (mentionsStyle) { - this.mentionsStyle = mentionsStyle; - return; - } - if (!this.messageObject) { - return; - } - const isMessageSentByLoggedInUser = - this.messageObject.getSender().getUid() === - CometChatUIKit.loggedInUser!.getUid(); - if (isMessageSentByLoggedInUser) { - this.mentionsStyle = { - selfTextStyle: { - color: "#30A46C", - }, - textStyle: { - color: "#FFFFFF", - }, - }; - } else { - this.mentionsStyle = { - selfTextStyle: { - color: "#30A46C", - }, - textStyle: { - color: "#D6409F", - }, - }; - } - } -} -``` +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- - +### LoadingView -**Example** +Custom component displayed during the loading state. - - - +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in loading indicator | -#### HeaderView +--- -This method allows you to set a custom header view for the message list. By providing a View object, you can customize the appearance and content of the header displayed at the top of the message list. +### messageRequestBuilder -Use Cases: +Controls which messages load and in what order. -* Add a custom branding/logo to the chat. -* Display chat status ("John is typing..."). -* Show last seen status. +| | | +| --- | --- | +| Type | `CometChat.MessagesRequestBuilder` | +| Default | SDK default | - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code - -const getMessageListHeaderView = ({ - user, - group, - id, -}: { - user?: CometChat.User; - group?: CometChat.Group; - id?: { - uid?: string; - guid?: string; - parentMessageId?: string; - }; -}) => { - //return jsx; -}; - -return ( - -); -``` +UID/GUID are always overridden internally. - +--- - +### NewMessageIndicatorView -**Example** +Custom view for the "New Messages" indicator. - - - +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in indicator | -*** +--- -#### FooterView +### onAddReactionPress -This method allows you to set a custom footer view for the message list. By providing a View object, you can customize the appearance and content of the footer displayed at the bottom of the message list. +Callback fired when the "Add More Reactions" button is clicked. -Use Cases: +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -* Add quick reply buttons. -* Display typing indicators ("John is typing..."). -* Show a disclaimer or privacy notice. +--- - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code - -const getMessageListFooterView = ({ - user, - group, - id, -}: { - user?: CometChat.User; - group?: CometChat.Group; - id?: { - uid?: string; - guid?: string; - parentMessageId?: string; - }; -}) => { - //return jsx; -}; - -return ( - -); -``` +### onEmpty - +Callback fired when the message list is empty. - +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -**Example** +--- - - - +### onError -*** +Callback fired when the component encounters an error. -#### NewMessageIndicatorView +| | | +| --- | --- | +| Type | `(error: CometChat.CometChatException) => void` | +| Default | `undefined` | -Custom view component for the "New Messages" indicator. +--- -Use Cases: +### onLoad -* Create a unique design for the new message notification. -* Add animation or custom behavior to the indicator. +Callback fired when messages are loaded. - - -```tsx -import { CometChatMessageList } from "@cometchat/chat-uikit-react-native"; -import { View, Text, TouchableOpacity } from 'react-native'; -import { CometChat } from "@cometchat/chat-sdk-react-native"; +| | | +| --- | --- | +| Type | `(messageList: CometChat.BaseMessage[]) => void` | +| Default | `undefined` | -const CustomNewMessageIndicator = () => { - return ( - - ⬇ New Messages - - ); -}; - -return ( - -); -``` - - +--- + +### onReactionLongPress + +Callback fired when a reaction is long-pressed. + +| | | +| --- | --- | +| Type | `(reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void` | +| Default | `undefined` | + +--- + +### onReactionPress + +Callback fired when a reaction is clicked. + +| | | +| --- | --- | +| Type | `(reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void` | +| Default | `undefined` | + +--- + +### onSuggestedMessageClick + +Callback fired when a suggested message is clicked. + +| | | +| --- | --- | +| Type | `(suggestion: string) => void` | +| Default | `undefined` | + +--- + +### onThreadRepliesPress + +Callback fired when a threaded message reply count is clicked. + +| | | +| --- | --- | +| Type | `(messageObject: CometChat.BaseMessage, messageBubbleView: () => JSX.Element \| null) => void` | +| Default | `undefined` | + +--- + +### parentMessageId + +Displays threaded conversation for the specified parent message. + +| | | +| --- | --- | +| Type | `number` | +| Default | `undefined` | + +--- + +### quickReactionList + +Custom list of quick reactions. + +| | | +| --- | --- | +| Type | `string[]` | +| Default | Predefined reactions | + +--- + +### receiptsVisibility + +Shows/hides read/delivery receipt indicators. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | + +--- + +### scrollToBottomOnNewMessage + +Auto-scrolls to bottom when new messages arrive. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### searchKeyword + +Keyword to highlight in message text. + +| | | +| --- | --- | +| Type | `string` | +| Default | `undefined` | + +--- + +### showMarkAsUnreadOption + +Shows "Mark Unread" option in message actions. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### startFromUnreadMessages + +Loads from the first unread message if available. + +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | + +--- + +### suggestedMessages + +Predefined prompts for AI assistant chats. + +| | | +| --- | --- | +| Type | `string[]` | +| Default | `undefined` | + +--- + +### templates + +Custom message bubble templates. Replaces all default templates. + +| | | +| --- | --- | +| Type | `CometChatMessageTemplate[]` | +| Default | SDK defaults | + +--- + +### addTemplates + +Additional message templates to append to the default templates. + +| | | +| --- | --- | +| Type | `CometChatMessageTemplate[]` | +| Default | `[]` | + +--- + +### newMessageIndicatorStyle + +Custom styles for the "New Messages" indicator. + +| | | +| --- | --- | +| Type | `NewMessageIndicatorStyle` | +| Default | Built-in style | + +--- + +### newMessageIndicatorText + +Custom text for the "New Messages" indicator. + +| | | +| --- | --- | +| Type | `string` | +| Default | Built-in text | + +--- + +### streamingSpeed + +Speed in milliseconds for AI response streaming animation. + +| | | +| --- | --- | +| Type | `number` | +| Default | `undefined` | + +--- + +### aiAssistantTools + +Tool actions for AI assistant functionality. + +| | | +| --- | --- | +| Type | `CometChatAIAssistantTools` | +| Default | `undefined` | + +--- + +### textFormatters + +Custom text formatters for message content. + +| | | +| --- | --- | +| Type | `CometChatTextFormatter[]` | +| Default | Default formatters from data source | + +--- + +### user + +The user for 1-on-1 conversation messages. + +| | | +| --- | --- | +| Type | `CometChat.User` | +| Default | `undefined` | + +--- + +## Next Steps + + + + Display user or group details in the chat toolbar + + + Compose and send messages in a chat + + + Complete messaging interface with header, list, and composer + + + Customize the appearance of UI Kit components + + \ No newline at end of file diff --git a/ui-kit/react-native/methods.mdx b/ui-kit/react-native/methods.mdx index 97c858afc..02e9f2474 100644 --- a/ui-kit/react-native/methods.mdx +++ b/ui-kit/react-native/methods.mdx @@ -1,34 +1,207 @@ --- title: "Methods" +description: "Initialize, authenticate, and send messages using CometChatUIKit methods in React Native UI Kit." --- -`CometChatUIKit` is a class that contains all necessary methods to help initialize the [CometChat SDK](/sdk/react-native/overview) with valid credentials for the ui kit to utilize. + -The following properties and methods are present: +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Import | `import { CometChatUIKit, UIKitSettings } from "@cometchat/chat-uikit-react-native";` | +| Init | `CometChatUIKit.init(UIKitSettings)` | +| Login (dev) | `CometChatUIKit.login({ uid: "UID" })` | +| Login (prod) | `CometChatUIKit.login({ authToken: "AUTH_TOKEN" })` | +| Other methods | `CometChatUIKit.logout()`, `CometChatUIKit.createUser(user)`, `CometChatUIKit.updateUser(user)` | +| Send messages | `CometChatUIKit.sendTextMessage()`, `CometChatUIKit.sendMediaMessage()`, `CometChatUIKit.sendCustomMessage()` | +| Interactive messages | `CometChatUIKit.sendFormMessage()`, `CometChatUIKit.sendCardMessage()`, `CometChatUIKit.sendCustomInteractiveMessage()` | +| Note | Use these wrapper methods instead of raw SDK calls — they manage internal UI Kit eventing | -| Parameters | Type | Description | -| -------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | -| **init** | static init(uiKitSettings: UIKitSettings): Promise\ | method initializes the settings required for CometChat SDK. First, ensure `authSettings` is set and then call the `init()` method on app startup | -| **login** | static async login(\{ uid, authToken }: \{ uid?: string, authToken?: string }): Promise\ | used for logging in with credentials but use this function only for testing purpose | -| **logout** | static logout(): Promise\ | used for ending user session of logged in user | -| **createUser** | static createUser( user: CometChat.User): Promise\ | used for creating new user | -| **updateUser** | static updateUser(user: CometChat.User): Promise\ \{ | used for updating user object | -| **sendCustomMessage** | static sendCustomMessage(message: CometChat.CustomMessage, onSuccess?: (msg: CometChat.CustomMessage \| CometChat.BaseMessage) => void, onError?: (msg: CometChat.CometChatException) => void): void | can be used to send a custom message | -| **sendTextMessage** | static sendTextMessage(message: CometChat.TextMessage, onSuccess?: (msg: CometChat.TextMessage \| CometChat.BaseMessage) => void, onError?: (msg: CometChat.CometChatException) => void): void | can be used to send a text message | -| **sendMediaMessage** | static sendMediaMessage(message: CometChat.CustomMessage, onSuccess?: (msg: CometChat.MediaMessage \| CometChat.BaseMessage) => void, onError?: (msg: CometChat.CometChatException) => void): void | can be used to send a media message | -| **sendFormMessage** | static sendFormMessage(message: FormMessage, disableLocalEvents: boolean = false): Promise\ | can be used to send a form message. disableLocalEvents - A boolean indicating whether to disable local events or not. Default value is false. | -| **sendCardMessage** | static sendCardMessage(message: CardMessage, disableLocalEvents: boolean = false): Promise\ | can be used to send a card message. disableLocalEvents - A boolean indicating whether to disable local events or not. Default value is false. | -| **sendCustomInteractiveMessage** | static sendCustomInteractiveMessage(message: CustomInteractiveMessage, disableLocalEvents: boolean = false): Promise\ | can be used to send a custom interactive message. disableLocalEvents - A boolean indicating whether to disable local events or not. Default value is false. | + -*** +The UI Kit wraps the [Chat SDK](/sdk/react-native/overview) methods to manage internal eventing and keep UI components synchronized. Use these wrapper methods instead of raw SDK calls. -### sendTextMessage + +`CometChatUIKit.init(UIKitSettings)` must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login. + -Used to send text messages. + +Auth Key is for development/testing only. In production, generate Auth Tokens on the server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + +## Methods + +All methods are accessed via the `CometChatUIKit` class. + +### Init + +Initializes the [CometChat React Native SDK](/sdk/react-native/overview). Must be called on app startup before any other UI Kit method. + + +Replace `APP_ID`, `REGION`, and `AUTH_KEY` with values from the CometChat Dashboard. `Auth Key` is optional — use [Auth Token](#login-using-auth-token) for production. + + + + +```js +import { CometChatUIKit, UIKitSettings } from "@cometchat/chat-uikit-react-native"; + +const uikitSettings = new UIKitSettings({ + appId: "APP_ID", // Replace with your App ID + region: "REGION", // Replace with your App Region ("eu" or "us") + authKey: "AUTH_KEY", // Replace with your Auth Key (optional for Auth Token flow) +}); + +CometChatUIKit.init(uikitSettings) + .then(() => { + console.log("Initialization completed successfully"); + }) + .catch((error) => { + console.log("Initialization failed with exception:", error); + }); +``` + + + +--- + +### Login using Auth Key + +Simple authentication for development/POC. For production, use [Auth Token](#login-using-auth-token). + + + +```js +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; + +const uid = "user_uid"; + +CometChatUIKit.login({ uid: uid }) + .then((user) => { + console.log("User logged in successfully:", user); + }) + .catch((error) => { + console.log("Login failed with exception:", error); + }); +``` + + + +--- + +### Login using Auth Token + +Production-safe authentication that does not expose the Auth Key in client code. + +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. + + + +```js +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; + +const authToken = "AUTH_TOKEN"; + +CometChatUIKit.login({ authToken: authToken }) + .then((user) => { + console.log("User logged in successfully:", user); + }) + .catch((error) => { + console.log("Login failed with exception:", error); + }); +``` + + + +--- + +### Logout + +Ends the current user session. + + + +```js +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; + +CometChatUIKit.logout(); +``` + + + +--- + +### Create User + +Takes a `User` object and returns the created `User` object. + + + +```js +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; + +const uid = "user1"; +const name = "Kevin"; +const avatar = "https://example.com/avatar.png"; + +const user = new CometChat.User(uid, name); +user.setAvatar(avatar); + +CometChatUIKit.createUser(user) + .then((user) => { + console.log("User created:", user); + }) + .catch((error) => { + console.log("Creating new user failed:", error); + }); +``` + + + +--- + +### Update User + +Takes a `User` object and returns the updated `User` object. - -```ts + +```js +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; + +const uid = "user1"; +const name = "Kevin Fernandez"; +const avatar = "https://example.com/new-avatar.png"; + +const user = new CometChat.User(uid, name); +user.setAvatar(avatar); + +CometChatUIKit.updateUser(user) + .then((user) => { + console.log("User updated:", user); + }) + .catch((error) => { + console.log("Updating user failed:", error); + }); +``` + + + +--- + +## Sending Messages + +### Text Message + +Sends a text message in a 1:1 or group chat. + + + +```js import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatUIKit, @@ -50,18 +223,18 @@ CometChatUIKit.sendTextMessage(textMessage) }) .catch(console.log); ``` - - -### sendMediaMessage +--- + +### Media Message -used to send media messages +Sends a media message in a 1:1 or group chat. - -```ts + +```js import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatUIKit, @@ -84,18 +257,18 @@ CometChatUIKit.sendMediaMessage(mediaMessage) }) .catch(console.log); ``` - - -### sendCustomMessage +--- -Used to send custom messages. +### Custom Message + +Sends a custom message (neither text nor media) in a 1:1 or group chat. - -```ts + +```js import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatUIKit, @@ -118,26 +291,29 @@ const customMessage = new CometChat.CustomMessage( CometChatUIKit.sendCustomMessage(customMessage) .then((message) => { - console.log("custom message sent successfully", message); + console.log("Custom message sent successfully", message); }) .catch(console.log); ``` - - -### Send Form message +--- + +## Interactive Messages -This method allows you to send Form messages which are the extension of Interactive Message +### Form Message + +Sends a Form message which is an extension of Interactive Message. - + ```js -import { CometChat } from "@cometchat/chat-sdk-react-native"; //import sdk package -import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; //import uikit package +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; const receiverID = "UID"; + // Create an instance of APIAction let apiAction = new APIAction("https://example.com/api", "POST"); @@ -146,8 +322,8 @@ let submitButton = new ButtonElement("1", apiAction, "Submit"); // Create an instance of TextInput let nameInput = new TextInputElement("1", "Please enter your name"); -// Create a new instance of FormMessage +// Create a new instance of FormMessage let formMessage = new FormMessage( receiverID, CometChat.RECEIVER_TYPE.USER, @@ -156,46 +332,32 @@ let formMessage = new FormMessage( submitButton ); -const onSuccessSend = (message) => { - console.log("Form message sent successfully", message); -}; - -const onErrorSend = (error: CometChat.CometChatException) => { - console.log("Form message sent error", error); -}; - -CometChatUIKit.sendFormMessage( - formMessage, - undefined, - onSuccessSend, - onErrorSend -); +CometChatUIKit.sendFormMessage(formMessage) + .then((message) => { + console.log("Form message sent successfully", message); + }) + .catch(console.log); ``` - - - + ```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package -import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package -import { - CometChatUIKitConstants, - APIAction, - ButtonElement, - TextInput, - FormMessage, -} from "@cometchat/uikit-resources"; //import shared package +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; const receiverID = "GUID"; + // Create an instance of APIAction let apiAction = new APIAction("https://example.com/api", "POST"); + // Create an instance of ButtonElement let submitButton = new ButtonElement("1", apiAction, "Submit"); + // Create an instance of TextInput -let nameInput = new TextInput("1", "Please enter your name"); +let nameInput = new TextInputElement("1", "Please enter your name"); + // Create a new instance of FormMessage let formMessage = new FormMessage( - "receiverId", + receiverID, CometChat.RECEIVER_TYPE.GROUP, "Title", [nameInput], @@ -208,74 +370,62 @@ CometChatUIKit.sendFormMessage(formMessage) }) .catch(console.log); ``` - - -### Send Card message +--- -This method allows you to send Card messages which are the extension of Interactive Message +### Card Message + +Sends a Card message which is an extension of Interactive Message. - + ```js -import { CometChat } from "@cometchat/chat-sdk-react-native"; //import sdk package -import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; //import uikit package +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; const receiverID = "UID"; + // Create instance of ButtonElement for card actions let cardAction = new ButtonElement( "1", new APIAction("https://example.com/api", "POST"), "Click Me" ); + // Create a new instance of CardMessage let cardMessage = new CardMessage( - "receiverId", + receiverID, CometChat.RECEIVER_TYPE.USER, "This is a card", [cardAction] ); -const onSuccessSend = (message) => { - console.log("Card message sent successfully", message); -}; - -const onErrorSend = (error: CometChat.CometChatException) => { - console.log("Card message sent error", error); -}; - -CometChatUIKit.sendCardMessage( - cardMessage, - undefined, - onSuccessSend, - onErrorSend -); +CometChatUIKit.sendCardMessage(cardMessage) + .then((message) => { + console.log("Card message sent successfully", message); + }) + .catch(console.log); ``` - - - + ```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package -import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package -import { - CometChatUIKitConstants, - ButtonElement, - CardMessage, -} from "@cometchat/uikit-resources"; //import shared package +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; const receiverID = "GUID"; + // Create instance of ButtonElement for card actions let cardAction = new ButtonElement( "1", new APIAction("https://example.com/api", "POST"), "Click Me" ); + // Create a new instance of CardMessage let cardMessage = new CardMessage( - "receiverId", + receiverID, CometChat.RECEIVER_TYPE.GROUP, "This is a card", [cardAction] @@ -283,67 +433,53 @@ let cardMessage = new CardMessage( CometChatUIKit.sendCardMessage(cardMessage) .then((message) => { - console.log("card message sent successfully", message); + console.log("Card message sent successfully", message); }) .catch(console.log); ``` - - -### Send CustomInteractive message +--- + +### Custom Interactive Message -This method allows you to send CustomInteractive messages which are the extension of Interactive Message +Sends a CustomInteractive message which is an extension of Interactive Message. - + ```js -import { CometChat } from "@cometchat/chat-sdk-react-native"; //import sdk package -import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; //import uikit package +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; const receiverID = "UID"; -// Create a new instance of CardMessage +const customData = { /* your custom JSON data */ }; + let customMessage = new CustomInteractiveMessage( - "receiverId", + receiverID, CometChat.RECEIVER_TYPE.USER, - json + customData ); -const onSuccess = (message) => { - console.log("Card message sent successfully", message); -}; - -const onError = (error: CometChat.CometChatException) => { - console.log("Card message sent error", error); -}; - -CometChatUIKit.sendCustomInteractiveMessage( - cardMessage, - undefined, - onSuccess, - onError -); +CometChatUIKit.sendCustomInteractiveMessage(customMessage) + .then((message) => { + console.log("CustomInteractive message sent successfully", message); + }) + .catch(console.log); ``` - - - + ```js -import { CometChat } from "@cometchat/chat-sdk-javascript"; //import sdk package -import { CometChatUIKit } from "@cometchat/chat-uikit-react"; //import uikit package -import { - CometChatUIKitConstants, - ButtonElement, - CardMessage, -} from "@cometchat/uikit-resources"; //import shared package +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; const receiverID = "GUID"; -// Create a new instance of CardMessage +const customData = { /* your custom JSON data */ }; + let customMessage = new CustomInteractiveMessage( - "receiverId", + receiverID, CometChat.RECEIVER_TYPE.GROUP, - json + customData ); CometChatUIKit.sendCustomInteractiveMessage(customMessage) @@ -352,180 +488,42 @@ CometChatUIKit.sendCustomInteractiveMessage(customMessage) }) .catch(console.log); ``` - - -## UIKitSettings - -UIKitSettings is an object containing credentials to initialize CometChat SDK. - -| Properties | Type | Description | -| ----------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------ | -| appId | string | the unique ID for the app, available on dashboard | -| region | string | the region for the app `us` or `eu` | -| authKey | string | the auth key for the app, available on dashboard | -| subscriptionType | string | sets user presence subscription for all users | -| autoEstablishSocketConnection | Bool | configure if web socket connections will established automatically on app initialization or be done manually, set to true by default | -| disableCalling | boolean | disable calling | -| overrideAdminHost | string | used to set the admin host | -| overrideClientHost | string | used to set the client host | - -*** - -## How to initialize the UI Kit? - -The UI Kit can be initialized to use CometChatUIKit by populating the auth settings first and the calling the init method. Preferably this should be done at the top most level when the app starts. - - - -Make sure you replace the **APP\_ID**, **REGION** and **AUTH\_KEY** with your CometChat App ID, Region and Auth Key in the below code. The `Auth Key` is an optional property of the `UIKitSettings` Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the [Auth Token](#how-to-login-a-user-with-auth-token) method to log in securely. - - - - - -```js -//CometChatUIKit should be initialized at the start of application. No need to initialize it again - -import {CometChatUIKit} from "@cometchat/chat-uikit-react-native"; - -let uikitSettings = UIKitSettings({ - APP_ID: "APP_ID", // Replace with your App ID - REGION: "REGION", // Replace with your App Region ("eu" or "us") - AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key or leave blank if you are authenticating using Auth Token - }) - -CometChatUIKit.init(uikitSettings) - .then(user => { - console.log("Initialization completed successfully") - }) - .catch(error => { - console.log( "Initialization failed with exception:",error) - }) -``` - - - - - -*** - -## How to login a user of your App? - -Only the `UID` of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use [AuthToken](#how-to-login-a-user-with-auth-token) instead of Auth Key. - - - -```js -let uid = <# Enter User's UID Here #> - -CometChatUIKit.login({uid: uid}) - .then(user => { - console.log("User logged in successfully") - catch(error => { - console.log("Login failed with exception:", error) - }) -``` - - - - - -*** - -## How to login a user with Auth Token? - -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({authToken: authToken})` method. - - - -```js -let authToken = <# Enter User's AuthToken Here #> - -CometChatUIKit.login({authToken: authToken}) - .then(user => { - console.log("User logged in successfully") - .catch(error => { - console.log("Login failed with exception:", error) - }) -``` - - - - - -## How to create a new user for your App? - -Create an object the new user that needs to created with as little information as the name of the user and a uid and pass it to the create(user: User) method - - - -```js -let uid = <# Enter User's UID Here #> -let name = <# Enter User Name Here #> -let avatar = <# Enter User's Avatar URL Here #> - -let user = new CometChat.User(uid,name) -user.setAvatar(avatar) - -CometChatUIKit.create(user) - .then(user => { - console.log("User created successfully") - .catch(error => { - console.log("Creating new user failed with exception:", error) - }) -``` - - - - - -## How to update a user for your App? - -Update an object the user that needs to updated with as little information as the name of the user and a uid and pass it to the `update(user: User)` method - - - -```js -let uid = <# Enter User's UID Here #> -let name = <# Enter Updated User Name Here #> -let avatar = <# Enter Updated User's Avatar URL Here #> - -let user = new CometChat.User(uidname) -user.setAvatar(avatar) - -CometChatUIKit.update(user) - .then(user => { - console.log("User updated successfully"); - }) - .catch(error => { - console.log("Updating user failed with exception:",error) - }) -``` - - +--- - +## UIKitSettings +`UIKitSettings` is an object containing credentials to initialize CometChat SDK. -### How to logout from a logged-In User in App? +| Property | Type | Description | +| --- | --- | --- | +| `appId` | `string` | The unique ID for the app, available on dashboard | +| `region` | `string` | The region for the app (`us` or `eu`) | +| `authKey` | `string` | The auth key for the app, available on dashboard | +| `subscriptionType` | `string` | Sets user presence subscription for all users | +| `autoEstablishSocketConnection` | `boolean` | Configure if web socket connections will be established automatically on app initialization (default: `true`) | +| `disableCalling` | `boolean` | Disable calling features | +| `overrideAdminHost` | `string` | Used to set the admin host | +| `overrideClientHost` | `string` | Used to set the client host | -just pass the loggedIn-user to the logout method - - -```js -import { CometChatUIKit } from '@cometchat/chat-uikit-react-native'; //import uikit package - -CometChatUIKit.logout(); -``` - - +--- - +## Next Steps + + + + Complete guide to integrating the UI Kit + + + Listen to UI Kit events for custom behavior + + + Explore all available UI components + + + Customize the look and feel of the UI Kit + + diff --git a/ui-kit/react-native/multi-tab-chat-ui-guide.mdx b/ui-kit/react-native/multi-tab-chat-ui-guide.mdx deleted file mode 100644 index 0e3a9fd30..000000000 --- a/ui-kit/react-native/multi-tab-chat-ui-guide.mdx +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: "Multi Tab Chat UI Guide" ---- - -This guide will help you achieve a tabbed layout (aka Multi-Tab Chat UI) of the components available in CometChatUIKit for React-native. - -We’ll use the [CometChatConversationsWithMessages](/ui-kit/react-native/conversations), [CometChatUsersWithMessages](/ui-kit/react-native/users-with-messages), and [CometChatGroupsWithMessages](/ui-kit/react-native/groups-with-messages) components and launch them as individual tab items within the tabbed layout. - -Step 1: Create a new component CometChatUI - - - -```tsx -export function CometChatUI() { - return ; -} -``` - - - - - -Step 2: Import the `CometChatTabs` component from the UI Kit. - - - -```tsx -import { CometChatTabs } from "@cometchat/chat-uikit-react-native"; - -export function CometChatUI() { - return ( - - - - ); -} -``` - - - - - -Step 3: Pass [CometChatConversationsWithMessages](/ui-kit/react-native/conversations), [CometChatUsersWithMessages](/ui-kit/react-native/users-with-messages), [CometChatGroupsWithMessages](/ui-kit/react-native/groups-with-messages) components to the Tabs components to launch them as individual tab item. We will also make the `CometChatConversationsWithMessages` tab the active tab by default. - - - -```tsx -import { - CometChatUsersWithMessages, - CometChatGroupsWithMessages, - CometChatConversationsWithMessages, - CometChatTabs, -} from "@cometchat/chat-uikit-react-native"; - -export function CometChatUI() { - const tabItemStyle: TabItemStyleInterface = { - activeBackgroundColor: "#6851D6", - }; - - const chatsTab: TabItem = { - id: "chats", - //iconURL: , - title: "Chats", - style: tabItemStyle, - isActive: true, - childView: () => , - }; - - const usersTab: TabItem = { - id: "users", - //iconURL: , - title: "Users", - style: tabItemStyle, - childView: () => , - }; - - const groupsTab: TabItem = { - id: "groups", - title: "Groups", - //iconURL: , - style: tabItemStyle, - childView: () => , - }; - - const tabs = [chatsTab, usersTab, groupsTab]; - - const tabsStyle = { - titleTextFont: theme.typography.heading, - titleTextColor: theme.palette.getAccent(), - tabHeight: 36, - tabBorderRadius: 18, - activeTabBackgroundColor: theme.palette.getPrimary(), - activeTabTitleTextColor: theme.palette.getSecondary(), - backgroundColor: theme.palette.getBackgroundColor(), - borderRadius: 18, - backIconTint: theme.palette.getPrimary(), - selectionIconTint: theme.palette.getPrimary(), - tabBackgroundColor: theme.palette.getAccent200(), - tabTitleTextColor: theme.palette.getAccent(), - tabTitleTextFont: theme.typography.text1, - }; - - return ( - - - - - - - - ); -} -``` - - - - - -Step 4: Import the CometChatUI component into your App component. - - - -```jsx -import { CometChatUI } from "./CometChatUI"; - -function App() { - const theme = new CometChatTheme({}); - theme.palette.setPrimary({ light: "#6851D6", dark: "#6851D6" }); - const [currentTheme, setCurrentTheme] = useState(theme); - - return ( - - - - - - ); -} - -export default App; -``` - - - - - -You can now see chats, users and group components each as tab items. This is how you can launch CometChat UIKit’s individual component in a tabbed layout. 🎉 - - - -![Image](/images/d14c1876-cometchat_ui_cometchat_screens-9adaaecb86825323a344913ff62919bc.png) - - - - -![Image](/images/dc3c428b-cometchat_ui_cometchat_screens-1cfd7755d9b7b5e83174c05c9d992d60.png) - - - - diff --git a/ui-kit/react-native/outgoing-call.mdx b/ui-kit/react-native/outgoing-call.mdx index 3ad735024..c1ada8174 100644 --- a/ui-kit/react-native/outgoing-call.mdx +++ b/ui-kit/react-native/outgoing-call.mdx @@ -1,37 +1,69 @@ --- title: "Outgoing Call" +description: "Display and manage outgoing voice and video calls with CometChatOutgoingCall component in React Native UI Kit, providing call status and controls." --- -## Overview + +```json +{ + "component": "CometChatOutgoingCall", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatOutgoingCall } from \"@cometchat/chat-uikit-react-native\";", + "description": "Visual representation for outgoing voice and video calls with call status and end call controls.", + "props": { + "data": { + "call": { + "type": "CometChat.Call | CometChat.CustomMessage", + "note": "The outgoing call object" + } + }, + "callbacks": { + "onEndCallButtonPressed": "(call: CometChat.Call) => void", + "onError": "(error: CometChat.CometChatException) => void" + }, + "sound": { + "disableSoundForCalls": { "type": "boolean", "default": false }, + "customSoundForCalls": { "type": "string", "default": "built-in" } + }, + "viewSlots": { + "TitleView": "(call) => JSX.Element", + "SubtitleView": "(call) => JSX.Element", + "AvatarView": "(call) => JSX.Element", + "EndCallView": "(call) => JSX.Element" + } + }, + "events": [ + { "name": "ccCallEnded", "payload": "{ call }", "description": "Call successfully ended" }, + { "name": "ccCallFailled", "payload": "{ call }", "description": "Error during call" } + ] +} +``` + + +## Where It Fits -The `CometChatOutgoingCall` [Component](/ui-kit/react-native/components-overview#components) is a visual representation of a user-initiated call, whether it's a voice or video call. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. This component typically includes information about the call recipient, call controls for canceling the call, and feedback on the call status, such as indicating when the call is in progress. +`CometChatOutgoingCall` is a [Component](/ui-kit/react-native/components-overview#components) that provides a visual representation of a user-initiated call, whether it's a voice or video call. It serves as an interface for managing outgoing calls, providing users with essential options to control the call experience. -*** - -## Usage - -### Integration +--- -`CometChatOutgoingCall` being a custom component, offers versatility in its integration. It can be seamlessly launched via button clicks or any user-triggered action, enhancing the overall user experience and facilitating smoother interactions within the application. +## Minimal Render - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; import { CometChatOutgoingCall, CometChatUiKitConstants, } from "@cometchat/chat-uikit-react-native"; +import { useState, useEffect } from "react"; -function App(): React.JSX.Element { +function OutgoingCallDemo() { const [call, setCall] = useState(); useEffect(() => { - //login const callObject = new CometChat.Call( "receiver-uid", CometChatUiKitConstants.MessageTypeConstants.audio, @@ -39,9 +71,7 @@ function App(): React.JSX.Element { ); CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) + .then((c) => setCall(c)) .catch(console.log); }, []); @@ -49,539 +79,272 @@ function App(): React.JSX.Element { } ``` - - - +--- -*** +## Actions and Events -### Actions +### Callback Props -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +#### onEndCallButtonPressed -##### onEndCallButtonPressed +Fires when the end call button is pressed. -The `onEndCallButtonPressed` action is typically triggered when the end call button is pressed, carrying out default actions. However, with the following code snippet, you can effortlessly customize or override this default behavior to meet your specific needs. +```tsx lines +onEndCallButtonPressed?: (call: CometChat.Call) => void +``` - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatOutgoingCall, - CometChatUiKitConstants, -} from "@cometchat/chat-uikit-react-native"; - -function App(): React.JSX.Element { - const [call, setCall] = useState(); - - useEffect(() => { - //login - const callObject = new CometChat.Call( - "receiver-uid", - CometChatUiKitConstants.MessageTypeConstants.audio, - CometChatUiKitConstants.ReceiverTypeConstants.user - ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react-native"; +function OutgoingCallWithEndButton() { const cancelCall = (c: CometChat.Call) => { - //code CometChat.endCall(c.getSessionId()).then(() => { setCall(undefined); }); }; return ( - <> - {call && ( - - )} - + ); } ``` - - - +#### onError -*** +Fires on internal errors (network failure, auth issue, SDK exception). -##### onError - -You can customize this behavior by using the provided code snippet to override the onError and improve error handling. +```tsx lines +onError?: (error: CometChat.CometChatException) => void +``` - - -```tsx +```tsx lines +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatOutgoingCall, - CometChatUiKitConstants, -} from "@cometchat/chat-uikit-react-native"; - -function App(): React.JSX.Element { - const [call, setCall] = useState(); - - useEffect(() => { - //login - const callObject = new CometChat.Call( - "receiver-uid", - CometChatUiKitConstants.MessageTypeConstants.audio, - CometChatUiKitConstants.ReceiverTypeConstants.user - ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const cancelCall = (c: CometChat.Call) => { - //code - CometChat.endCall(c.getSessionId()).then(() => { - setCall(undefined); - }); - }; +function OutgoingCallWithError() { return ( - <> - {call && ( - { - console.log('Handle error:', err); - } - /> - )} - + { + console.error("OutgoingCall error:", error); + }} + /> ); } ``` - - - - -*** - -### Filters +### Global UI Events -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Add listeners and remove them on cleanup. -The OutgoingCall component does not have any exposed filters. +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccCallEnded` | Initiated call successfully ends | `{ call }` | +| `ccCallFailled` | Error occurs during the initiated call | `{ call }` | -*** +When to use: sync external UI with call state changes. For example, update a call status indicator, show notifications, or log call events. -### Events - -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. - -The list of events emitted by the Incoming Call component is as follows. - -| Event | Description | -| ----------------- | ---------------------------------------------------------------------- | -| **ccCallEnded** | This event is triggered when the initiated call successfully ends. | -| **ccCallFailled** | This event is triggered when an error occurs during the intiated call. | - - - -```tsx +```tsx lines +import { useEffect } from "react"; import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallEnded: ({ call }) => { - //code - }, -}); - -CometChatUIEventHandler.addCallListener("CALL_LISTENER_ID", { - ccCallFailled: ({ call }) => { - //code - }, -}); -``` - - - - - -*** - - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +function useOutgoingCallEvents() { + useEffect(() => { + const listenerId = "OUTGOING_CALL_EVENTS_" + Date.now(); + + CometChatUIEventHandler.addCallListener(listenerId, { + ccCallEnded: ({ call }) => { + console.log("Call ended:", call); + }, + ccCallFailled: ({ call }) => { + console.log("Call failed:", call); + }, + }); -CometChatUIEventHandler.removeCallListener("CALL_LISTENER_ID"); + return () => { + CometChatUIEventHandler.removeCallListener(listenerId); + }; + }, []); +} ``` - +--- - +## Custom View Slots -*** +Each slot replaces a section of the default UI. Slots that accept a call parameter receive the call object for customization. -## Customization +| Slot | Signature | Replaces | +| --- | --- | --- | +| `TitleView` | `(call) => JSX.Element` | Caller name / title text | +| `SubtitleView` | `(call) => JSX.Element` | Call status text | +| `AvatarView` | `(call) => JSX.Element` | Avatar / profile picture | +| `EndCallView` | `(call) => JSX.Element` | End call button | -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +### TitleView -### Style +Custom view for the caller name / title text. -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +```tsx lines +TitleView?: (call: CometChat.Call | CometChat.CustomMessage) => JSX.Element +``` - - -```tsx +```tsx lines +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatOutgoingCall, - CometChatUiKitConstants, -} from "@cometchat/chat-uikit-react-native"; - -function App(): React.JSX.Element { - const [call, setCall] = useState(); - - useEffect(() => { - //login - const callObject = new CometChat.Call( - "receiver-uid", - CometChatUiKitConstants.MessageTypeConstants.audio, - CometChatUiKitConstants.ReceiverTypeConstants.user - ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); +import { Text } from "react-native"; - const cancelCall = (c: CometChat.Call) => { - //code - CometChat.endCall(c.getSessionId()).then(() => { - setCall(undefined); - }); +function TitleViewDemo() { + const getTitleView = (call: CometChat.Call | CometChat.CustomMessage) => { + const receiver = call.getCallReceiver(); + return {receiver.getName()}; }; - return ( - <> - {call && ( - - )} - - ); + return ; } ``` - - - - - - - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets - -| Methods | Description | Code | -| ------------------------ | --------------------------------------------------------------------------------- | ---------------------------------------------------- | -| **call** | Sets the call object for CometChatOutgoingCall | `call?: CometChat.Call `\| `CometChat.CustomMessage` | -| **callSettingsBuilder** | Sets the CallSettingsBuilder for the outgoing call configuration. | `callSettingsBuilder={callSettingsBuilderObject}` | -| **customSoundForCalls** | Used to set custom sound for calls | `customSoundForCalls?: string` | -| **disableSoundForCalls** | Used to disable/enable the sound of Outgoing calls, by default it is set to false | `disableSoundForCalls?: boolean` | - -*** - -### Advanced - -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -#### TitleView +### SubtitleView -Allows setting a custom list item view to be rendered for each conversation in the fetched call list. +Custom view for the call status text. -Use Cases: - -* Display the contact’s name in a unique style. -* Show a call type indicator (Voice Call, Video Call). -* Add status text like "Calling..." or "Ringing...". +```tsx lines +SubtitleView?: (call: CometChat.Call | CometChat.CustomMessage) => JSX.Element +``` - - -```tsx +```tsx lines +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatOutgoingCall, - CometChatUiKitConstants, -} from "@cometchat/chat-uikit-react-native"; - -function App(): React.JSX.Element { - const [call, setCall] = useState(); - - useEffect(() => { - //login - const callObject = new CometChat.Call( - "receiver-uid", - CometChatUiKitConstants.MessageTypeConstants.audio, - CometChatUiKitConstants.ReceiverTypeConstants.user - ); +import { Text } from "react-native"; - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const cancelCall = (c: CometChat.Call) => { - //code - CometChat.endCall(c.getSessionId()).then(() => { - setCall(undefined); - }); +function SubtitleViewDemo() { + const getSubtitleView = (call: CometChat.Call | CometChat.CustomMessage) => { + return Calling...; }; - return ( - <> - {call && ( - { - //return jsx; - }} - /> - )} - - ); + return ; } ``` - - - - -#### SubtitleView - -Enables customizing the subtitle view, typically used for additional call details. +### AvatarView -Use Cases: +Custom view for the avatar / profile picture. -* Display call duration if available. -* Show network strength indicators. -* Include a custom message like "Connecting...". +```tsx lines +AvatarView?: (call: CometChat.Call | CometChat.CustomMessage) => JSX.Element +``` - - -```tsx +```tsx lines +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatOutgoingCall, - CometChatUiKitConstants, -} from "@cometchat/chat-uikit-react-native"; - -function App(): React.JSX.Element { - const [call, setCall] = useState(); - - useEffect(() => { - //login - const callObject = new CometChat.Call( - "receiver-uid", - CometChatUiKitConstants.MessageTypeConstants.audio, - CometChatUiKitConstants.ReceiverTypeConstants.user +import { View, Text } from "react-native"; + +function AvatarViewDemo() { + const getAvatarView = (call: CometChat.Call | CometChat.CustomMessage) => { + const receiver = call.getCallReceiver(); + return ( + + + {receiver.getName().charAt(0)} + + ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const cancelCall = (c: CometChat.Call) => { - //code - CometChat.endCall(c.getSessionId()).then(() => { - setCall(undefined); - }); }; - return ( - <> - {call && ( - { - //return jsx; - }} - /> - )} - - ); + return ; } ``` - - - +### EndCallView -#### AvatarView +Custom view for the end call button. -Allows setting a custom leading view, usually used for the contact’s profile picture or avatar. - -Use Cases: - -* Show a profile picture with an online indicator. -* Display a custom icon based on the call type (Voice/Video). -* Use an animated ring effect around the avatar when calling. +```tsx lines +EndCallView?: (call: CometChat.Call | CometChat.CustomMessage) => JSX.Element +``` - - -```tsx +```tsx lines +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatOutgoingCall, - CometChatUiKitConstants, -} from "@cometchat/chat-uikit-react-native"; - -function App(): React.JSX.Element { - const [call, setCall] = useState(); - - useEffect(() => { - //login - const callObject = new CometChat.Call( - "receiver-uid", - CometChatUiKitConstants.MessageTypeConstants.audio, - CometChatUiKitConstants.ReceiverTypeConstants.user +import { TouchableOpacity, Text } from "react-native"; + +function EndCallViewDemo() { + const getEndCallView = (call: CometChat.Call | CometChat.CustomMessage) => { + return ( + CometChat.endCall(call.getSessionId())} + > + End Call + ); - - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); - - const cancelCall = (c: CometChat.Call) => { - //code - CometChat.endCall(c.getSessionId()).then(() => { - setCall(undefined); - }); }; - return ( - <> - {call && ( - { - //return jsx; - }} - /> - )} - - ); + return ; } ``` - - - - -#### EndCallView - -Defines a custom title view for the end call button, allowing modifications to the call termination UI. - -Use Cases: - -* Customize the "End Call" button style. -* Add a confirmation pop-up before ending the call. -* Display different icons based on call status (Active, On Hold). - - - -```tsx -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatOutgoingCall, - CometChatUiKitConstants, -} from "@cometchat/chat-uikit-react-native"; +--- -function App(): React.JSX.Element { - const [call, setCall] = useState(); +## Styling - useEffect(() => { - //login - const callObject = new CometChat.Call( - "receiver-uid", - CometChatUiKitConstants.MessageTypeConstants.audio, - CometChatUiKitConstants.ReceiverTypeConstants.user - ); +Using Style you can customize the look and feel of the component in your app. Pass a styling object as a prop to the `CometChatOutgoingCall` component. - CometChat.initiateCall(callObject) - .then((c) => { - setCall(c); - }) - .catch(console.log); - }, []); + + + - const cancelCall = (c: CometChat.Call) => { - //code - CometChat.endCall(c.getSessionId()).then(() => { - setCall(undefined); - }); - }; +```tsx lines +import { CometChatOutgoingCall } from "@cometchat/chat-uikit-react-native"; +function StylingDemo() { return ( - <> - {call && ( - { - //return jsx; - }} - /> - )} - + ); } ``` - +### Visibility Props + +| Property | Description | Code | +| --- | --- | --- | +| `disableSoundForCalls` | Disable/enable the sound of outgoing calls | `disableSoundForCalls?: boolean` | +| `customSoundForCalls` | Set custom sound for outgoing calls | `customSoundForCalls?: string` | + +--- - +## Next Steps + + + + Display and handle incoming calls + + + Add voice and video call buttons to your UI + + + Overview of all calling features + + + Customize the appearance of UI Kit components + + diff --git a/ui-kit/react-native/overview.mdx b/ui-kit/react-native/overview.mdx index 61e193093..c5b7a61d7 100644 --- a/ui-kit/react-native/overview.mdx +++ b/ui-kit/react-native/overview.mdx @@ -1,24 +1,81 @@ --- -title: "Overview" +title: "React Native UI Kit" +sidebarTitle: "Overview" +description: "Prebuilt React Native components for chat, voice, and video calling. Supports React Native CLI and Expo." --- -With CometChat's UI Kit for React Native, you can effortlessly build a chat app equipped with all the essential messaging features, along with customizable options tailored to your application requirements. This UI Kit comprises prebuilt UI components organized into smaller modules and components, each configurable to meet your specific needs. + -## Before Getting Started +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` v5.x | +| Peer deps | `react-native` >=0.70, `@cometchat/chat-sdk-react-native`, `react-native-gesture-handler`, `react-native-safe-area-context` | +| Calling | Optional — `@cometchat/calls-sdk-react-native` | +| Localization | Built-in localization support | +| Source | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5) | -Before you begin, it's essential to grasp the fundamental concepts and features offered by CometChat's APIs, SDK, and UI Kit. You can find detailed information in [Key Concepts](/fundamentals/key-concepts) documentation. + -The UI Kit library comprises pre-built React Native Components for effortless integration and is built on top of the [React Native Chat SDK](/sdk/react-native/overview). Installing it will also include the core Chat SDK. +The CometChat React Native UI Kit provides prebuilt, customizable components for adding chat, voice, and video calling to any React Native app. Each component handles its own data fetching, real-time listeners, and state — you just drop them into your layout. -To begin, please follow the [Getting Started](/ui-kit/react-native/getting-started) guide. + + + -Quick Links + +`CometChatUIKit.init(UIKitSettings)` must be called before rendering any UI Kit components or calling any SDK methods. Initialization must complete before login. + - - - Ready-to-use app examples to kickstart your project. + +Auth Key is for development/testing only. In production, generate Auth Tokens on your server using the REST API and pass them to the client. Never expose Auth Keys in production client code. + + +--- + +## Get Started + +Pick your framework and follow the step-by-step integration guide: + + + + Standard React Native project setup + + } href="/ui-kit/react-native/expo-integration"> + Expo managed workflow + + + +--- + +## Explore + + + + Browse all prebuilt UI components + + + Chat, calling, AI, and extensions + + + Colors, fonts, dark mode, and custom styling + + + Initialize, authenticate, and send messages + + + +--- + +## Resources + + + + Working reference app + + + Full UI Kit source on GitHub - - Access the complete source code on GitHub. + + Open a support ticket diff --git a/ui-kit/react-native/property-changes.mdx b/ui-kit/react-native/property-changes.mdx index 0ddf07ffc..b13b0c8de 100644 --- a/ui-kit/react-native/property-changes.mdx +++ b/ui-kit/react-native/property-changes.mdx @@ -1,7 +1,19 @@ --- title: "Property Changes" +description: "Comprehensive reference of new, renamed, and removed properties for each CometChat React Native UI Kit v5 component." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Common renames | `ListItemView` → `ItemView`, `TailView` → `TrailingView`, `EmptyStateView` → `EmptyView`, `ErrorStateView` → `ErrorView` | +| Style changes | `[component]Style` → `style` (e.g., `conversationsStyle` → `style`), all use `DeepPartial<>` types | +| Migration guide | [Upgrading from V4](/ui-kit/react-native/upgrading-from-v4) | + + + ## Conversations ### New Properties @@ -141,7 +153,7 @@ title: "Property Changes" | `searchPlaceholderText` | string | Placeholder text for the search input. | | `selectionMode` | `'none' \| 'single' \| 'multiple'` | Selection mode: `'none'`, `'single'`, or `'multiple'`. | | `onSelection` | `(list: Array) => void` | Callback when group selection is complete. | -| `onSubmit` | `(list: Array) => void` | Callback when submit selection button is pressed. | +| `onSubmit` | `(list: Array) => void` | Callback when submit selection button is pressed. | | `hideSearch` | boolean | Hide the search box. | | `EmptyView` | `() => JSX.Element` | Custom view for the empty state. | | `ErrorView` | `() => JSX.Element` | Custom view for the error state. | @@ -208,7 +220,7 @@ title: "Property Changes" | `onItemPress` | `(groupMember: CometChat.GroupMember) => void` | Callback when a group member item is pressed. | | `onItemLongPress` | `(groupMember: CometChat.GroupMember) => void` | Callback when a group member item is long pressed. | | `onSelection` | `(list: CometChat.GroupMember[]) => void` | Callback when group member selection is complete. | -| `onSubmit` | `(list: Array) => void` | Callback when submit selection button is pressed. | +| `onSubmit` | `(list: Array) => void` | Callback when submit selection button is pressed. | | `searchRequestBuilder` | `CometChat.GroupMembersRequestBuilder` | Request builder for search functionality. | | `groupMemberRequestBuilder` | `CometChat.GroupMembersRequestBuilder` | Request builder to fetch group members. | | `group` | `CometChat.Group` | The group object for which members are listed. | @@ -634,4 +646,24 @@ title: "Property Changes" | `onInfoIconPress` | `(prop: { call: any }) => void` | Callback for info icon press. | | `infoIcon` | `ImageType` | Info icon image. | | `theme` | `CometChatTheme` | Theme configuration for the call logs component. | -| `hideSeperator` | `boolean` | Toggle visibility of separator. | \ No newline at end of file +| `hideSeperator` | `boolean` | Toggle visibility of separator. | + + +--- + +## Next Steps + + + + Overview of architectural changes between v4 and v5 + + + Learn the v5 approach to styling individual components + + + Customize colors, fonts, and styles with the theme provider + + + Set up the v5 UI Kit from scratch + + diff --git a/ui-kit/react-native/react-native-cli-integration.mdx b/ui-kit/react-native/react-native-cli-integration.mdx new file mode 100644 index 000000000..375f9be07 --- /dev/null +++ b/ui-kit/react-native/react-native-cli-integration.mdx @@ -0,0 +1,346 @@ +--- +title: "React Native CLI Integration" +sidebarTitle: "Integration" +description: "Add CometChat to a React Native CLI app in 5 steps: create project, install, init, login, render." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Peer deps | `react-native` >=0.77.0, `@cometchat/chat-sdk-react-native` | +| Init | `CometChatUIKit.init(UIKitSettings)` — must resolve before `login()` | +| Login | `CometChatUIKit.login({ uid })` — must resolve before rendering components | +| Order | `init()` → `login()` → render. Breaking this order = blank screen | +| Auth Key | Dev/testing only. Use Auth Token in production | +| Calling | Optional. Install `@cometchat/calls-sdk-react-native` to enable | +| Other frameworks | [Expo](/ui-kit/react-native/expo-integration) | + + + +This guide walks you through adding CometChat to a React Native CLI app. By the end you'll have a working chat UI. + +--- + +## Prerequisites + +You need three things from the [CometChat Dashboard](https://app.cometchat.com/): + +| Credential | Where to find it | +| --- | --- | +| App ID | Dashboard → Your App → Credentials | +| Auth Key | Dashboard → Your App → Credentials | +| Region | Dashboard → Your App → Credentials (e.g. `us`, `eu`, `in`) | + +You also need: +- Node.js (v16+) and npm/yarn installed +- React Native development environment set up ([React Native CLI Quickstart](https://reactnative.dev/docs/environment-setup)) +- Xcode (for iOS) and Android Studio (for Android) + + +Auth Key is for development only. In production, generate Auth Tokens server-side via the [REST API](https://api-explorer.cometchat.com/) and use [`loginWithAuthToken()`](/ui-kit/react-native/methods#how-to-login-a-user-with-auth-token). Never ship Auth Keys in client code. + + +--- + +## Step 1 — Create a React Native Project + +```bash +npx @react-native-community/cli init ChatApp +cd ChatApp +``` + + +The CometChat React Native UI Kit is officially built and tested with React Native version 0.77.0 and above. While it may work with older versions, they are not officially supported. + + +--- + +## Step 2 — Install the UI Kit + +```bash +npm install @cometchat/chat-uikit-react-native +``` + +This installs the UI Kit. You also need to install the SDK and peer dependencies: + +```bash +npm install @cometchat/chat-sdk-react-native +npm install @react-native-community/datetimepicker +npm install @react-native-clipboard/clipboard +npm install react-native-svg +npm install react-native-video +npm install dayjs +npm install @react-native-async-storage/async-storage +npm install react-native-gesture-handler +npm install react-native-localize +npm install react-native-safe-area-context +``` + +### Android: Add Local Maven Repository for Async Storage + + +**Android only:** `@react-native-async-storage/async-storage` v3 ships a local Maven artifact. Add this to your `android/build.gradle` or the Android build will fail. + + +```gradle title="android/build.gradle" +allprojects { + repositories { + google() + mavenCentral() + maven { + url = uri(project(":react-native-async-storage_async-storage").file("local_repo")) + } + } +} +``` + +### Add Permissions for Android + +Open `android/app/src/main/AndroidManifest.xml` and add: + +```xml + + + + + + +``` + +### Install iOS Pods + +```bash +cd ios && pod install && cd .. +``` + +### Configure Gesture Handler + +Add this import at the very top of your entry file (before any other imports): + +```js title="index.js" +import 'react-native-gesture-handler'; +``` + + +This import must be at the top of your entry file. Failing to do so may cause crashes in production. + + +### Optional: Install Calling SDK + +To enable voice/video calling: + +```bash +npm install @cometchat/calls-sdk-react-native +npm install @react-native-community/netinfo +npm install react-native-background-timer +npm install react-native-callstats +npm install react-native-webrtc +``` + +Add iOS permissions to `ios/ChatApp/Info.plist`: + +```xml +NSCameraUsageDescription +Camera access for video calls +NSMicrophoneUsageDescription +Microphone access for voice/video calls +``` + +--- + +## Step 3 — Initialize CometChat + + +`init()` must resolve before you call `login()`. If you call `login()` before init completes, it will fail silently. + + + + +```tsx +import { CometChatUIKit, UIKitSettings } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const COMETCHAT_CONSTANTS = { + APP_ID: "APP_ID", // Replace with your App ID + REGION: "REGION", // Replace with your Region + AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (dev only) +}; + +const uiKitSettings: UIKitSettings = { + appId: COMETCHAT_CONSTANTS.APP_ID, + authKey: COMETCHAT_CONSTANTS.AUTH_KEY, + region: COMETCHAT_CONSTANTS.REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], +}; + +CometChatUIKit.init(uiKitSettings) + .then(() => { + console.log("CometChat UI Kit initialized successfully."); + }) + .catch((error) => { + console.error("CometChat UI Kit initialization failed:", error); + }); +``` + + +```jsx +import { CometChatUIKit } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const COMETCHAT_CONSTANTS = { + APP_ID: "APP_ID", // Replace with your App ID + REGION: "REGION", // Replace with your Region + AUTH_KEY: "AUTH_KEY", // Replace with your Auth Key (dev only) +}; + +const uiKitSettings = { + appId: COMETCHAT_CONSTANTS.APP_ID, + authKey: COMETCHAT_CONSTANTS.AUTH_KEY, + region: COMETCHAT_CONSTANTS.REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, +}; + +CometChatUIKit.init(uiKitSettings) + .then(() => { + console.log("CometChat UI Kit initialized successfully."); + }) + .catch((error) => { + console.error("CometChat UI Kit initialization failed:", error); + }); +``` + + + +--- + +## Step 4 — Login + +After init resolves, log the user in. For development, use one of the pre-created test UIDs: + +`cometchat-uid-1` · `cometchat-uid-2` · `cometchat-uid-3` · `cometchat-uid-4` · `cometchat-uid-5` + + + +```tsx +const UID = "cometchat-uid-1"; // Replace with your actual UID + +CometChatUIKit.login({ uid: UID }) + .then((user: CometChat.User) => { + console.log("Login Successful:", user.getName()); + }) + .catch((error) => { + console.error("Login failed:", error); + }); +``` + + +```jsx +const UID = "cometchat-uid-1"; // Replace with your actual UID + +CometChatUIKit.login({ uid: UID }) + .then((user) => { + console.log("Login Successful:", user.getName()); + }) + .catch((error) => { + console.error("Login failed:", error); + }); +``` + + + + +For production, use [`loginWithAuthToken()`](/ui-kit/react-native/methods#how-to-login-a-user-with-auth-token) instead of Auth Key. Generate tokens server-side via the REST API. + + +--- + +## Step 5 — Choose a Chat Experience + +Integrate a conversation view that suits your app's UX. Each option below includes a step-by-step guide. + +### Conversation List + Message View + +List of conversations on one screen, tap to open messages. Standard mobile chat pattern. + +- Conversation list with real-time updates +- Tap-to-view — tapping a conversation opens the message view +- Switch between one-to-one and group conversations +- Back navigation to return to the list + + + + + + + Step-by-step guide to build this layout + + +--- + +### One-to-One / Group Chat + +Single chat window — no conversation list. Good for support chat, embedded widgets, or focused messaging. + +- Dedicated chat window for one-on-one or group messaging +- No conversation list — users go directly into the chat +- Full-screen experience +- Ideal for support chat or community messaging + + + + + + + Step-by-step guide to build this layout + + +--- + +### Tab-Based Chat + +Tabbed navigation — Chats, Users, Groups, Calls in separate tabs. Good for full-featured apps. + +- Tab navigation between Chats, Users, Groups, and Calls +- Full-screen messaging within each tab +- Uses React Navigation bottom tabs +- Scales well for adding future features + + + + + + + Step-by-step guide to build this layout + + +--- + +## Build Your Own Chat Experience + +Need full control over the UI? Use individual components, customize themes, and wire up your own layouts. + +- [Sample App](https://github.com/cometchat/cometchat-uikit-react-native) — Working reference app to compare against +- [Components](/ui-kit/react-native/components-overview) — All prebuilt UI elements with props and customization options +- [Core Features](/ui-kit/react-native/core-features) — Messaging, real-time updates, and other capabilities +- [Theming](/ui-kit/react-native/theme) — Colors, fonts, dark mode, and custom styling + +--- + +## Next Steps + + + + Browse all prebuilt UI components + + + Customize colors, fonts, and styles + + + Chat features included out of the box + + + Explore init, login, logout, and other UI Kit methods + + diff --git a/ui-kit/react-native/react-native-conversation.mdx b/ui-kit/react-native/react-native-conversation.mdx new file mode 100644 index 000000000..c8981561f --- /dev/null +++ b/ui-kit/react-native/react-native-conversation.mdx @@ -0,0 +1,390 @@ +--- +title: "Conversation List + Message View" +sidebarTitle: "Conversation List + Message View" +description: "Build a conversation list + message view layout in React Native with CometChat UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Framework | React Native CLI | +| Components | `CometChatConversations`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Conversation list → tap → message view | +| Prerequisite | Complete [React Native CLI Integration](/ui-kit/react-native/react-native-cli-integration) Steps 1–4 first | +| Pattern | WhatsApp, Telegram, Signal | + + + +This guide builds a standard mobile chat layout — conversation list on one screen, tap to open messages. Users tap a conversation to view and send messages. + +This assumes you've already completed [React Native CLI Integration](/ui-kit/react-native/react-native-cli-integration) (project created, UI Kit installed, init + login working). + + + + + +--- + +## What You're Building + +Two screens working together: + +1. **Conversation list** — shows all active conversations (users and groups) +2. **Message view** — displays chat messages for the selected conversation with header, message list, and composer + +--- + +## Step 1 — Create the Messages Component + +Create a `Messages.tsx` file that combines the message header, list, and composer: + + + +```tsx title="Messages.tsx" +import React from "react"; +import { View, StyleSheet } from "react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +interface MessagesProps { + user?: CometChat.User; + group?: CometChat.Group; + onBack: () => void; +} + +const Messages = ({ user, group, onBack }: MessagesProps) => { + return ( + + + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, +}); + +export default Messages; +``` + + +```jsx title="Messages.js" +import React from "react"; +import { View, StyleSheet } from "react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; + +const Messages = ({ user, group, onBack }) => { + return ( + + + + + + ); +}; + +const styles = StyleSheet.create({ + container: { + flex: 1, + }, +}); + +export default Messages; +``` + + + +Key points: +- `CometChatMessageHeader` shows the recipient's name, avatar, and back button +- `CometChatMessageList` displays the chat history with real-time updates +- `CometChatMessageComposer` provides the text input with media, emojis, and send button +- Pass either `user` or `group` to the components, never both + +--- + +## Step 2 — Update App.tsx + +Wire the conversation list and message components together: + + + +```tsx title="App.tsx" +import React, { useEffect, useState } from "react"; +import { ViewStyle } from "react-native"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatConversations, + CometChatUIKit, + CometChatUiKitConstants, + UIKitSettings, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import Messages from "./Messages"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const App = (): React.ReactElement => { + const [loggedIn, setLoggedIn] = useState(false); + const [messageUser, setMessageUser] = useState(); + const [messageGroup, setMessageGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings: UIKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings + .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + const handleConversationPress = (conversation: CometChat.Conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + setMessageUser(conversation.getConversationWith() as CometChat.User); + setMessageGroup(undefined); + } else { + setMessageUser(undefined); + setMessageGroup(conversation.getConversationWith() as CometChat.Group); + } + }; + + const handleBack = () => { + setMessageUser(undefined); + setMessageGroup(undefined); + }; + + return ( + + + + + + {loggedIn && ( + <> + {/* Conversation list (hidden when chat is open) */} + + + {/* Message view */} + {(messageUser || messageGroup) && ( + + )} + + )} + + + + + + ); +}; + +const styles: { fullScreen: ViewStyle } = { + fullScreen: { flex: 1 }, +}; + +export default App; +``` + + +```jsx title="App.js" +import React, { useEffect, useState } from "react"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatConversations, + CometChatUIKit, + CometChatUiKitConstants, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import Messages from "./Messages"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const App = () => { + const [loggedIn, setLoggedIn] = useState(false); + const [messageUser, setMessageUser] = useState(); + const [messageGroup, setMessageGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + const handleConversationPress = (conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + setMessageUser(conversation.getConversationWith()); + setMessageGroup(undefined); + } else { + setMessageUser(undefined); + setMessageGroup(conversation.getConversationWith()); + } + }; + + const handleBack = () => { + setMessageUser(undefined); + setMessageGroup(undefined); + }; + + return ( + + + + + + {loggedIn && ( + <> + {/* Conversation list (hidden when chat is open) */} + + + {/* Message view */} + {(messageUser || messageGroup) && ( + + )} + + )} + + + + + + ); +}; + +export default App; +``` + + + +How it works: +- `CometChatConversations` renders the list of conversations +- `onItemPress` fires when a user taps a conversation, extracting the `User` or `Group` +- `messageUser` / `messageGroup` state drives which chat is displayed +- The conversation list is hidden (via `display: "none"`) when a chat is open +- `handleBack` clears the selection and returns to the conversation list + +--- + +## Step 3 — Run the Project + + + +```bash +npx react-native run-ios +``` + + +```bash +npx react-native run-android +``` + + + +You should see the conversation list. Tap any conversation to open the message view. Use the back button to return to the list. + +--- + +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/react-native/react-native-one-to-one-chat.mdx b/ui-kit/react-native/react-native-one-to-one-chat.mdx new file mode 100644 index 000000000..b58be693a --- /dev/null +++ b/ui-kit/react-native/react-native-one-to-one-chat.mdx @@ -0,0 +1,341 @@ +--- +title: "One-to-One / Group Chat" +sidebarTitle: "One-to-One / Group Chat" +description: "Build a focused one-to-one or group chat experience in React Native with CometChat UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Framework | React Native CLI | +| Components | `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Single chat window — no conversation list | +| Prerequisite | Complete [React Native CLI Integration](/ui-kit/react-native/react-native-cli-integration) Steps 1–4 first | +| Pattern | Support chat, embedded widgets, focused messaging | + + + +This guide builds a single chat window — no conversation list. Users go directly into a one-to-one or group chat. Good for support chat, embedded widgets, or any focused messaging experience. + +This assumes you've already completed [React Native CLI Integration](/ui-kit/react-native/react-native-cli-integration) (project created, UI Kit installed, init + login working). + + + + + +--- + +## What You're Building + +Three components stacked vertically: + +1. **Chat header** — displays recipient name, avatar, online status, and optional call buttons +2. **Message list** — real-time chat history with scrolling +3. **Message composer** — text input with media, emojis, and send button + +No additional files to create — everything goes in `App.tsx`. + +--- + +## Step 1 — Update App.tsx + +The app fetches a user (or group) on mount and renders the three message components. + + + +```tsx title="App.tsx" +import React, { useEffect, useState } from "react"; +import { View, Text, StyleSheet } from "react-native"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatUIKit, + UIKitSettings, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const LOGIN_UID = "cometchat-uid-1"; + +// The user or group to chat with +const CHAT_WITH_UID = "cometchat-uid-2"; // Replace with actual UID +// const CHAT_WITH_GUID = "GUID"; // Uncomment for group chat + +const App = (): React.ReactElement => { + const [loggedIn, setLoggedIn] = useState(false); + const [selectedUser, setSelectedUser] = useState(); + const [selectedGroup, setSelectedGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings: UIKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings + .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: LOGIN_UID }); + setLoggedIn(true); + + // Fetch the user to chat with + const user = await CometChat.getUser(CHAT_WITH_UID); + setSelectedUser(user); + + // For group chat, uncomment below: + // const group = await CometChat.getGroup(CHAT_WITH_GUID); + // setSelectedGroup(group); + } catch (err) { + console.error("Init/login/fetch error:", err); + } + }; + + init(); + }, []); + + return ( + + + + + + {loggedIn && (selectedUser || selectedGroup) ? ( + + + + + + ) : ( + + + Set a user or group UID in App.tsx to start chatting + + + )} + + + + + + ); +}; + +const styles = StyleSheet.create({ + fullScreen: { + flex: 1, + }, + messagesWrapper: { + flex: 1, + }, + emptyState: { + flex: 1, + justifyContent: "center", + alignItems: "center", + backgroundColor: "#F5F5F5", + }, + emptyText: { + color: "#727272", + fontSize: 14, + }, +}); + +export default App; +``` + + +```jsx title="App.js" +import React, { useEffect, useState } from "react"; +import { View, Text, StyleSheet } from "react-native"; +import { SafeAreaProvider, SafeAreaView } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatUIKit, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const LOGIN_UID = "cometchat-uid-1"; + +// The user or group to chat with +const CHAT_WITH_UID = "cometchat-uid-2"; // Replace with actual UID +// const CHAT_WITH_GUID = "GUID"; // Uncomment for group chat + +const App = () => { + const [loggedIn, setLoggedIn] = useState(false); + const [selectedUser, setSelectedUser] = useState(); + const [selectedGroup, setSelectedGroup] = useState(); + + useEffect(() => { + const init = async () => { + const uiKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: LOGIN_UID }); + setLoggedIn(true); + + // Fetch the user to chat with + const user = await CometChat.getUser(CHAT_WITH_UID); + setSelectedUser(user); + + // For group chat, uncomment below: + // const group = await CometChat.getGroup(CHAT_WITH_GUID); + // setSelectedGroup(group); + } catch (err) { + console.error("Init/login/fetch error:", err); + } + }; + + init(); + }, []); + + return ( + + + + + + {loggedIn && (selectedUser || selectedGroup) ? ( + + + + + + ) : ( + + + Set a user or group UID in App.tsx to start chatting + + + )} + + + + + + ); +}; + +const styles = StyleSheet.create({ + fullScreen: { + flex: 1, + }, + messagesWrapper: { + flex: 1, + }, + emptyState: { + flex: 1, + justifyContent: "center", + alignItems: "center", + backgroundColor: "#F5F5F5", + }, + emptyText: { + color: "#727272", + fontSize: 14, + }, +}); + +export default App; +``` + + + +Key points: +- `CometChat.getUser(UID)` fetches the user object from the SDK — you need a real user object, not a manually constructed one +- Pass either `user` or `group` to the message components, never both +- The highlighted constants show where to set the UID or swap to group chat + +--- + +## Switching Between User and Group Chat + +To load a group chat instead of one-to-one, replace the `getUser` call with `getGroup`: + +```tsx +const CHAT_WITH_GUID = "GUID"; // Replace with your actual Group ID + +const group = await CometChat.getGroup(CHAT_WITH_GUID); +setSelectedGroup(group); +``` + +You can also determine this dynamically — for example, based on a route parameter or a selection from another part of your app. + +--- + +## Step 2 — Run the Project + + + +```bash +npx react-native run-ios +``` + + +```bash +npx react-native run-android +``` + + + +You should see the chat window load with the conversation for the UID you set. + +--- + +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/react-native/react-native-tab-based-chat.mdx b/ui-kit/react-native/react-native-tab-based-chat.mdx new file mode 100644 index 000000000..0e64583c0 --- /dev/null +++ b/ui-kit/react-native/react-native-tab-based-chat.mdx @@ -0,0 +1,687 @@ +--- +title: "Tab-Based Chat" +sidebarTitle: "Tab-Based Chat" +description: "Build a tab-based messaging UI with Chats, Users, Groups, and Calls in React Native with CometChat UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Framework | React Native CLI | +| Components | `CometChatConversations`, `CometChatUsers`, `CometChatGroups`, `CometChatCallLogs`, `CometChatMessageHeader`, `CometChatMessageList`, `CometChatMessageComposer` | +| Layout | Tabbed navigation (Chats, Users, Groups, Calls) + message view | +| Prerequisite | Complete [React Native CLI Integration](/ui-kit/react-native/react-native-cli-integration) Steps 1–4 first | +| Pattern | Full-featured messaging app with multiple sections | + + + +This guide builds a tabbed messaging UI — Chats, Users, Groups, and Calls tabs with bottom navigation, plus a message view when an item is selected. Good for full-featured apps that need more than just conversations. + +This assumes you've already completed [React Native CLI Integration](/ui-kit/react-native/react-native-cli-integration) (project created, UI Kit installed, init + login working). + + + + + +--- + +## What You're Building + +Three sections working together: + +1. **Tab bar** — switches between Chats, Users, Groups, and Calls +2. **List screens** — renders the list for the active tab +3. **Message view** — header + messages + composer for the selected item + +--- + +## Prerequisites + +Install React Navigation dependencies: + +```bash +npm install @react-navigation/native @react-navigation/bottom-tabs @react-navigation/native-stack +npm install react-native-screens +``` + +For iOS, install pods: + +```bash +cd ios && pod install && cd .. +``` + +### Configure Gesture Handler + +Add this import at the very top of your entry file (before any other imports): + +```js title="index.js" +import 'react-native-gesture-handler'; +``` + + +This import must be at the top of your entry file. Failing to do so may cause crashes in production. + + +--- + +## Step 1 — Create the Tab Screens + +Create individual screen components for each tab: + + + +```tsx title="screens/ConversationsScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { + CometChatConversations, + CometChatUiKitConstants, +} from "@cometchat/chat-uikit-react-native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type Props = { + navigation: NativeStackNavigationProp; +}; + +export function ConversationsScreen({ navigation }: Props) { + const handleItemPress = (conversation: CometChat.Conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + const user = conversation.getConversationWith() as CometChat.User; + navigation.navigate("Messages", { user }); + } else { + const group = conversation.getConversationWith() as CometChat.Group; + navigation.navigate("Messages", { group }); + } + }; + + return ( + + + + ); +} +``` + +```tsx title="screens/UsersScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type Props = { + navigation: NativeStackNavigationProp; +}; + +export function UsersScreen({ navigation }: Props) { + const handleItemPress = (user: CometChat.User) => { + navigation.navigate("Messages", { user }); + }; + + return ( + + + + ); +} +``` + +```tsx title="screens/GroupsScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type Props = { + navigation: NativeStackNavigationProp; +}; + +export function GroupsScreen({ navigation }: Props) { + const handleItemPress = (group: CometChat.Group) => { + navigation.navigate("Messages", { group }); + }; + + return ( + + + + ); +} +``` + +```tsx title="screens/CallLogsScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; + +export function CallLogsScreen() { + return ( + + + + ); +} +``` + + +```jsx title="screens/ConversationsScreen.js" +import React from "react"; +import { View } from "react-native"; +import { + CometChatConversations, + CometChatUiKitConstants, +} from "@cometchat/chat-uikit-react-native"; + +export function ConversationsScreen({ navigation }) { + const handleItemPress = (conversation) => { + const conversationType = conversation.getConversationType(); + + if (conversationType === CometChatUiKitConstants.ConversationTypeConstants.user) { + const user = conversation.getConversationWith(); + navigation.navigate("Messages", { user }); + } else { + const group = conversation.getConversationWith(); + navigation.navigate("Messages", { group }); + } + }; + + return ( + + + + ); +} +``` + +```jsx title="screens/UsersScreen.js" +import React from "react"; +import { View } from "react-native"; +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; + +export function UsersScreen({ navigation }) { + const handleItemPress = (user) => { + navigation.navigate("Messages", { user }); + }; + + return ( + + + + ); +} +``` + +```jsx title="screens/GroupsScreen.js" +import React from "react"; +import { View } from "react-native"; +import { CometChatGroups } from "@cometchat/chat-uikit-react-native"; + +export function GroupsScreen({ navigation }) { + const handleItemPress = (group) => { + navigation.navigate("Messages", { group }); + }; + + return ( + + + + ); +} +``` + +```jsx title="screens/CallLogsScreen.js" +import React from "react"; +import { View } from "react-native"; +import { CometChatCallLogs } from "@cometchat/chat-uikit-react-native"; + +export function CallLogsScreen() { + return ( + + + + ); +} +``` + + + +--- + +## Step 2 — Create the Messages Screen + + + +```tsx title="screens/MessagesScreen.tsx" +import React from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; +import { RouteProp } from "@react-navigation/native"; +import { NativeStackNavigationProp } from "@react-navigation/native-stack"; + +type MessagesRouteParams = { + Messages: { + user?: CometChat.User; + group?: CometChat.Group; + }; +}; + +type Props = { + route: RouteProp; + navigation: NativeStackNavigationProp; +}; + +export function MessagesScreen({ route, navigation }: Props) { + const { user, group } = route.params; + + return ( + + navigation.goBack()} + showBackButton + /> + + + + ); +} +``` + + +```jsx title="screens/MessagesScreen.js" +import React from "react"; +import { View } from "react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; + +export function MessagesScreen({ route, navigation }) { + const { user, group } = route.params; + + return ( + + navigation.goBack()} + showBackButton + /> + + + + ); +} +``` + + + +--- + +## Step 3 — Set Up Navigation + +Configure React Navigation with bottom tabs and a stack navigator: + + + +```tsx title="App.tsx" +import React, { useEffect, useState } from "react"; +import { Image, StyleSheet } from "react-native"; +import { NavigationContainer } from "@react-navigation/native"; +import { createNativeStackNavigator } from "@react-navigation/native-stack"; +import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatUIKit, + UIKitSettings, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +import { ConversationsScreen } from "./screens/ConversationsScreen"; +import { UsersScreen } from "./screens/UsersScreen"; +import { GroupsScreen } from "./screens/GroupsScreen"; +import { CallLogsScreen } from "./screens/CallLogsScreen"; +import { MessagesScreen } from "./screens/MessagesScreen"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const Tab = createBottomTabNavigator(); +const Stack = createNativeStackNavigator(); + +function TabNavigator() { + return ( + + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + + ); +} + +export default function App() { + const [loggedIn, setLoggedIn] = useState(false); + + useEffect(() => { + const init = async () => { + const uiKitSettings: UIKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings + .SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"], + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + if (!loggedIn) return null; + + return ( + + + + + + + + + + + + + + + ); +} + +const styles = StyleSheet.create({ + tabBar: { + backgroundColor: "#FFFFFF", + borderTopWidth: 1, + borderTopColor: "#E8E8E8", + paddingBottom: 5, + paddingTop: 5, + height: 60, + }, + tabIcon: { + width: 24, + height: 24, + }, +}); +``` + + +```jsx title="App.js" +import React, { useEffect, useState } from "react"; +import { Image, StyleSheet } from "react-native"; +import { NavigationContainer } from "@react-navigation/native"; +import { createNativeStackNavigator } from "@react-navigation/native-stack"; +import { createBottomTabNavigator } from "@react-navigation/bottom-tabs"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { + CometChatUIKit, + CometChatThemeProvider, + CometChatI18nProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; + +import { ConversationsScreen } from "./screens/ConversationsScreen"; +import { UsersScreen } from "./screens/UsersScreen"; +import { GroupsScreen } from "./screens/GroupsScreen"; +import { CallLogsScreen } from "./screens/CallLogsScreen"; +import { MessagesScreen } from "./screens/MessagesScreen"; + +const APP_ID = "APP_ID"; +const AUTH_KEY = "AUTH_KEY"; +const REGION = "REGION"; +const UID = "cometchat-uid-1"; + +const Tab = createBottomTabNavigator(); +const Stack = createNativeStackNavigator(); + +function TabNavigator() { + return ( + + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + ( + + ), + }} + /> + + ); +} + +export default function App() { + const [loggedIn, setLoggedIn] = useState(false); + + useEffect(() => { + const init = async () => { + const uiKitSettings = { + appId: APP_ID, + authKey: AUTH_KEY, + region: REGION, + subscriptionType: CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS, + }; + + try { + await CometChatUIKit.init(uiKitSettings); + await CometChatUIKit.login({ uid: UID }); + setLoggedIn(true); + } catch (err) { + console.error("Init/login error:", err); + } + }; + + init(); + }, []); + + if (!loggedIn) return null; + + return ( + + + + + + + + + + + + + + + ); +} + +const styles = StyleSheet.create({ + tabBar: { + backgroundColor: "#FFFFFF", + borderTopWidth: 1, + borderTopColor: "#E8E8E8", + paddingBottom: 5, + paddingTop: 5, + height: 60, + }, + tabIcon: { + width: 24, + height: 24, + }, +}); +``` + + + + +Download tab icons from the [CometChat UI Kit assets folder on GitHub](https://github.com/cometchat/cometchat-uikit-react-native) and place them in your `assets/` folder. + + +--- + +## Step 4 — Run the Project + + + +```bash +npx react-native run-ios +``` + + +```bash +npx react-native run-android +``` + + + +You should see the tab bar at the bottom. Switch between Chats, Users, Groups, and Calls — tapping any item navigates to the message view. + +--- + +## Next Steps + + + + Customize colors, fonts, and styles to match your brand + + + Browse all prebuilt UI components + + + Back to the main setup guide + + + Chat features included out of the box + + diff --git a/ui-kit/react-native/shortcut-formatter-guide.mdx b/ui-kit/react-native/shortcut-formatter-guide.mdx index df7ab8ba6..4795ec2e3 100644 --- a/ui-kit/react-native/shortcut-formatter-guide.mdx +++ b/ui-kit/react-native/shortcut-formatter-guide.mdx @@ -1,91 +1,173 @@ --- title: "ShortCut Formatter" +description: "Create custom text shortcuts for quick message composition by extending CometChatTextFormatter in React Native." --- -## Introduction + -The `ShortCutFormatter` class extends the `CometChatTextFormatter` class to provide a mechanism for handling shortcuts within messages. This guide will walk you through the process of using ShortCutFormatter to implement shortcut extensions in your CometChat application. +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key class | `CometChatTextFormatter` (abstract base class for custom formatters) | +| Required setup | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Create custom text shortcuts for quick message composition by extending CometChatTextFormatter | +| Extension | Message Shortcuts extension must be enabled in [CometChat Dashboard](https://app.cometchat.com) | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/sample) | +| Related | [Mentions Formatter](/ui-kit/react-native/mentions-formatter-guide) · [Custom Text Formatter](/ui-kit/react-native/custom-text-formatter-guide) · [All Guides](/ui-kit/react-native/guide-overview) | -## Setup + -1. **Create the ShortCutFormatter Class**: Define the ShortCutFormatter class by extending the CometChatTextFormatter class. +## Overview - - -```ts -import { CometChat } from "@cometchat/chat-sdk-react-native"; -import { - CometChatTextFormatter, - SuggestionItem, -} from "@cometchat/chat-uikit-react-native"; +The `ShortCutFormatter` class extends the `CometChatTextFormatter` class to provide a mechanism for handling shortcuts within messages. This guide walks you through the process of using ShortCutFormatter to implement shortcut extensions in your CometChat application. -export class ShortCutFormatter extends CometChatTextFormatter { - constructor() { - super(); - this.trackCharacter = "!"; - } -} -``` + +The Message Shortcuts extension must be enabled in your [CometChat Dashboard](https://app.cometchat.com) for this feature to work. + - +--- - +## Setup -2. **Override Search Method**: Override the search() method to search for shortcuts based on the entered search text. + + + Define the ShortCutFormatter class by extending the CometChatTextFormatter class: - - -```ts -search = (searchKey: string) => { - let data: Array = []; - - CometChat.callExtension("message-shortcuts", "GET", "v1/fetch", undefined) - .then((data: any) => { - if (data && data?.shortcuts) { - let suggestionData = Object.keys(data.shortcuts).map((key) => { - return new SuggestionItem({ - id: key, - name: data.shortcuts[key], - promptText: data.shortcuts[key], - trackingCharacter: "!", - underlyingText: data.shortcuts[key], - }); - }); - this.setSearchData(suggestionData); // setting data in setSearchData(); + + + ```tsx + import { CometChat } from "@cometchat/chat-sdk-react-native"; + import { + CometChatTextFormatter, + SuggestionItem, + } from "@cometchat/chat-uikit-react-native"; + + export class ShortCutFormatter extends CometChatTextFormatter { + constructor() { + super(); + this.trackCharacter = "!"; // Character that triggers shortcut suggestions } - }) - .catch((error) => { - // Some error occured - }); + } + ``` + + + ```jsx + import { CometChat } from "@cometchat/chat-sdk-react-native"; + import { + CometChatTextFormatter, + SuggestionItem, + } from "@cometchat/chat-uikit-react-native"; - this.setSearchData(data); -}; + export class ShortCutFormatter extends CometChatTextFormatter { + constructor() { + super(); + this.trackCharacter = "!"; // Character that triggers shortcut suggestions + } + } + ``` + + + -// return null in fetchNext, if there's no pagination. -fetchNext = () => { - return null; -}; -``` + + Override the `search()` method to fetch shortcuts based on the entered search text: - + + + ```tsx + search = (searchKey: string) => { + CometChat.callExtension("message-shortcuts", "GET", "v1/fetch", undefined) + .then((data: any) => { + if (data && data?.shortcuts) { + let suggestionData = Object.keys(data.shortcuts) + .filter((key) => + searchKey + ? key.toLowerCase().includes(searchKey.toLowerCase()) + : true + ) + .map((key) => { + return new SuggestionItem({ + id: key, + name: data.shortcuts[key], + promptText: data.shortcuts[key], + trackingCharacter: "!", + underlyingText: data.shortcuts[key], + }); + }); + this.setSearchData(suggestionData); + } + }) + .catch((error) => { + console.error("Error fetching shortcuts:", error); + }); + }; - + // Return null in fetchNext if there's no pagination + fetchNext = () => { + return null; + }; + ``` + + + ```jsx + search = (searchKey) => { + CometChat.callExtension("message-shortcuts", "GET", "v1/fetch", undefined) + .then((data) => { + if (data && data?.shortcuts) { + let suggestionData = Object.keys(data.shortcuts) + .filter((key) => + searchKey + ? key.toLowerCase().includes(searchKey.toLowerCase()) + : true + ) + .map((key) => { + return new SuggestionItem({ + id: key, + name: data.shortcuts[key], + promptText: data.shortcuts[key], + trackingCharacter: "!", + underlyingText: data.shortcuts[key], + }); + }); + this.setSearchData(suggestionData); + } + }) + .catch((error) => { + console.error("Error fetching shortcuts:", error); + }); + }; + + // Return null in fetchNext if there's no pagination + fetchNext = () => { + return null; + }; + ``` + + + + + +--- ## Usage -1. **Initialization**: Initialize an instance of `ShortCutFormatter` in your application. +Initialize an instance of `ShortCutFormatter` and pass it to the message composer via the `textFormatters` prop: - + ```tsx import React from "react"; +import { View } from "react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; import { - CometChatMessages, - CometChatMentionsFormatter, + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, } from "@cometchat/chat-uikit-react-native"; +// Import your custom ShortCutFormatter class defined above +import { ShortCutFormatter } from "./ShortCutFormatter"; -function App(): React.JSX.Element { +function ChatScreen(): React.JSX.Element { const [chatUser, setChatUser] = React.useState(); React.useEffect(() => { @@ -94,36 +176,97 @@ function App(): React.JSX.Element { }); }, []); - const shortcutFormatter = new ShortCutFormatter(); + const shortcutFormatter = React.useMemo(() => new ShortCutFormatter(), []); return ( <> {chatUser && ( - + + + + + )} ); } -``` +export default ChatScreen; +``` + +```jsx +import React, { useState, useEffect, useMemo } from "react"; +import { View } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, +} from "@cometchat/chat-uikit-react-native"; +// Import your custom ShortCutFormatter class defined above +import { ShortCutFormatter } from "./ShortCutFormatter"; - +function ChatScreen() { + const [chatUser, setChatUser] = useState(); + + useEffect(() => { + CometChat.getUser("uid").then((user) => { + setChatUser(user); + }); + }, []); -## Example + const shortcutFormatter = useMemo(() => new ShortCutFormatter(), []); - - -![Image](/images/05765721-shortcutFormatter_cometchat_screens-517c2c6a37bba5955dbe20bd90ef0be8.png) + return ( + <> + {chatUser && ( + + + + + + )} + + ); +} +export default ChatScreen; +``` + + +--- - -![Image](/images/3e9305c0-shortcutFormatter_cometchat_screens-aaf76ef5aa3891a74e6aaa9d68635386.png) +## Result - +When users type the trigger character (`!`), they'll see a list of available shortcuts to quickly insert predefined text. - + + ShortCut Formatter + + +--- + +## Next Steps + + + + Format and style @mentions in chat messages + + + Customize the message input component + + + Browse all feature and formatter guides + + + Customize how messages are displayed + + \ No newline at end of file diff --git a/ui-kit/react-native/sound-manager.mdx b/ui-kit/react-native/sound-manager.mdx index c2fc808c5..eac401b41 100644 --- a/ui-kit/react-native/sound-manager.mdx +++ b/ui-kit/react-native/sound-manager.mdx @@ -1,53 +1,103 @@ --- title: "Sound Manager" +description: "Manage and customize audio cues for incoming/outgoing calls and messages in CometChat React Native UI Kit." --- -## Overview + -CometChatSoundManager is responsible for playing different types of audio which is required for incoming and outgoing events in UI Kit. It plays audio for incoming and outgoing messages as well as calls. +| Field | Value | +| --- | --- | +| Goal | Manage audio playback for incoming/outgoing calls and messages | +| Import | `import { CometChatSoundManager } from "@cometchat/chat-uikit-react-native";` | +| Play sound | `CometChatSoundManager.play("incomingMessage")` | +| Custom sound | `CometChatSoundManager.play("outgoingMessage", "path/to/sound.mp3")` | +| Pause sound | `CometChatSoundManager.pause()` | +| Sound events | `incomingMessage`, `incomingMessageFromOther`, `outgoingMessage`, `incomingCall`, `outgoingCall` | +| Default behavior | Plays built-in sounds; pass custom path as second arg to override | -Before you can use the SoundManager, it must be initialized: + - - -```ts -CometChatSoundManager.play("incomingMessage"); -``` +`CometChatSoundManager` is a helper class for managing and playing audio cues in the UI Kit — incoming/outgoing calls and messages. + +--- - +## Sound Events - +| Event Key | When It Plays | +| --- | --- | +| `incomingMessage` | New message received from current conversation | +| `incomingMessageFromOther` | New message received from a different conversation | +| `outgoingMessage` | Message sent | +| `incomingCall` | Incoming call detected (loops) | +| `outgoingCall` | Outgoing call initiated (loops) | + +--- ## Methods -### Play Sound +### play + +Plays the default or custom audio resource for a given sound event. + +| Parameter | Type | Description | +| --- | --- | --- | +| `sound` | `string` | Sound event key: `"incomingMessage"`, `"outgoingMessage"`, `"incomingCall"`, `"outgoingCall"` | +| `customSound` | `string` | Optional custom audio file path. Defaults to built-in sound. | +| `isRequire` | `boolean` | Optional. Set to `true` if using `require()` for local assets. | + +```ts +import { CometChatSoundManager } from "@cometchat/chat-uikit-react-native"; -The SoundManager plays pre-defined or custom sounds based on user interactions with the chat interface. If no custom sound file is provided, the default sound is played. +// Play default sound +CometChatSoundManager.play("incomingMessage"); -Here are the available methods for triggering sound playback: +// Play custom sound +CometChatSoundManager.play("outgoingMessage", "path/to/custom-sound.mp3"); +``` -* `play(sound, customSound, isRequire = false)`: This method is used for playing the sound for a particular state as mentioned in the Sound enum cases. This method plays different types of sounds for incoming call, outgoing call and messages. This method is also capable of playing in-built sounds or custom sounds by passing a mp3 file asset path as parameter mentioned in the method. If this parameter is null, it will play the default sound. Otherwise it will play the custom sound from the provided file path. +### pause -### Pause Sound +Pauses the currently playing sound and resets playback position. -The SoundManager can pause different types of sounds for incoming and outgoing calls and messages using the following method: +```ts +CometChatSoundManager.pause(); +``` -* `pause()`: This method pauses any sound currently being played. +--- ## Usage -Here is how to use CometChatSoundManager: +Here is how to use `CometChatSoundManager`: ```javascript // Play sound with default sound: -CometChatSoundManager.play("incomingMessage"); //To play default incoming message sound -CometChatSoundManager.play("outgoingMessage"); //To play default outgoing message sound +CometChatSoundManager.play("incomingMessage"); // To play default incoming message sound +CometChatSoundManager.play("outgoingMessage"); // To play default outgoing message sound -//Play sound with custom sound -CometChatSoundManager.play("outgoingMessage", "assetPath"); //To custom message sound +// Play sound with custom sound +CometChatSoundManager.play("outgoingMessage", "assetPath"); // To play custom message sound // Pause Sound: CometChatSoundManager.pause(); ``` -By using the CometChatSoundManager, you can enhance the user experience in your chat application by integrating audible cues for chat interactions. +By using the `CometChatSoundManager`, you can enhance the user experience in your chat application by integrating audible cues for chat interactions. + +--- + +## Next Steps + + + + Add multi-language support with automatic device language detection + + + Learn how CometChatThemeProvider manages light and dark modes + + + Explore all available UI Kit components + + + Set up CometChat UI Kit in your React Native app + + diff --git a/ui-kit/react-native/theme.mdx b/ui-kit/react-native/theme.mdx index d93599d7e..3dec55fd1 100644 --- a/ui-kit/react-native/theme.mdx +++ b/ui-kit/react-native/theme.mdx @@ -1,30 +1,97 @@ --- -title: "Introduction" +title: "Customizing UI With Theming" +sidebarTitle: "Overview" +description: "Customize the look and feel of CometChat React Native UI Kit components using themes, including light/dark modes, colors, typography, and component-specific styles." --- -## Overview + -Theming in CometChat for React Native allows you to create visually consistent and customizable user interfaces that align with your application's branding. The CometChatThemeProvider acts as a global theme provider, enabling seamless integration of light and dark modes while giving you the flexibility to define custom colors, typography, and component-specific styles. +| Field | Value | +| --- | --- | +| Goal | Customize UI Kit appearance (colors, fonts, dark mode) via theme provider | +| Provider | `CometChatThemeProvider` — wrap your app to enable theming | +| Import | `import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native";` | +| Set mode | `` or `"dark"` | +| Override colors | `theme={{ light: { color: { primary: "#F76808" } } }}` | +| Component styles | `theme={{ light: { conversationStyles: { ... } } }}` | +| Key tokens | `primary`, `textPrimary`, `background1`, `neutral50`, `extendedPrimary500` | +| Constraints | Colors must be hex values, theme merges with defaults (deep merge) | +| Full token list | [Colors](/ui-kit/react-native/colors) | [GitHub source](https://github.com/cometchat/cometchat-uikit-react-native/blob/v5/packages/ChatUiKit/src/theme/type.ts) | -At the core of theming is the CometChatTheme interface, which defines the structure of the theme supplied to the provider. This interface lets you specify various theme attributes such as colors, fonts, and component-level customizations. By wrapping your application with CometChatThemeProvider and supplying a CometChatTheme, you can maintain a consistent look and feel across all CometChat components while having full control over customizations to match your app’s aesthetic. + + +Theming controls the look and feel of the chat UI — colors, fonts, and component styles — through the `CometChatThemeProvider`. + + +Prerequisites: +1. Wrap your app with `CometChatThemeProvider` to enable theming +2. Wrap with `SafeAreaProvider` and `GestureHandlerRootView` for proper layout +3. Colors must be supplied as hex values (e.g., `#F76808`) +4. Theme values are deeply merged with defaults — only override what you need + + +--- + +## Theming Contract + +**Inputs** +- `CometChatThemeProvider` wrapper with optional `theme` prop +- Theme mode: `{ mode: "light" }` or `{ mode: "dark" }` +- Color overrides: `{ light: { color: { primary: "#F76808" } } }` +- Component-specific styles: `{ light: { conversationStyles: { ... } } }` + +**Precedence** +1. Style prop on component (highest priority) +2. Custom theme via `CometChatThemeProvider` +3. Default theme (lowest priority) + +**Outputs** +- Primary color changes buttons, outgoing bubbles, and active states +- Background tokens change panels and surfaces +- Typography tokens change fonts across the UI +- Component styles override specific component appearances + +--- + +## Top Tokens (Quick Mapping) + +For the complete list, see [Colors](/ui-kit/react-native/colors). + +| Token | Common Usage | +| --- | --- | +| `primary` | Primary accent color (buttons, outgoing bubbles, active states) | +| `extendedPrimary500` | Mid primary shade (secondary accents/hover) | +| `extendedPrimary900` | Darker primary shade (outgoing bubble shade) | +| `neutral50` | White/dark surface (light: `#FFFFFF`, dark: `#141414`) | +| `neutral300` | Neutral surface (incoming bubbles/panels) | +| `background1` | Main app background | +| `background2` | Secondary/panel background | +| `textPrimary` | Primary text color | +| `textSecondary` | Secondary/caption text | +| `info`, `warning`, `success`, `error` | Semantic state colors | + +--- ## Using Theming in Your Project By default, the theme is automatically selected based on the system settings, ensuring that your app aligns with the user's preferred light or dark mode unless you choose to override it with a custom theme. -The CometChatThemeProvider is used to apply a custom theme to your components. By setting the theme prop with a specific mode, such as `{ mode: 'dark' }`, you can override the default system theme and ensure that the UI is displayed in the desired light or dark mode. This allows you to provide a consistent visual experience based on the selected theme mode. +The `CometChatThemeProvider` is used to apply a custom theme to your components. By setting the theme prop with a specific mode, such as `{ mode: 'dark' }`, you can override the default system theme and ensure that the UI is displayed in the desired light or dark mode. This allows you to provide a consistent visual experience based on the selected theme mode. -To ensure the app dynamically adapts to the device's OS-level light or dark theme, it must be wrapped in the CometChatThemeProvider. Without this wrapper, system theme changes will not be reflected in the app's UI. +To ensure the app dynamically adapts to the device's OS-level light or dark theme, it must be wrapped in the `CometChatThemeProvider`. Without this wrapper, system theme changes will not be reflected in the app's UI. -Here’s an example of how to explicitly set the theme mode to `light`: +Here's an example of how to explicitly set the theme mode to `light`: ```ts +import { SafeAreaView } from "react-native-safe-area-context"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + return ( @@ -44,11 +111,14 @@ return ( ## Customization -To customize the primary color in your app, you can override the primary color attribute in the theme. Here's how to override the primary color for light theme: +To customize the primary color in your app, you can override the primary color attribute in the theme. Here's how to override the primary color for the light theme: ```ts +import { SafeAreaView } from "react-native-safe-area-context"; +import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native"; + return ( @@ -107,6 +177,7 @@ import { useTheme, } from "@cometchat/chat-uikit-react-native"; import { CometChatThemeProvider } from "@cometchat/chat-uikit-react-native/src/theme/provider"; +import { SafeAreaView } from "react-native-safe-area-context"; import Messages from "./src/Messages"; //other code @@ -168,7 +239,7 @@ return ( ### Supplying Custom Theme to Specific Components by wrapping them in a separate CometChatThemeProvider -Following is an example of how the theme for the CometChatConversations component is specifically overridden by wrapping it in a separate CometChatThemeProvider. This allows the CometChatConversations component to use a dark mode theme, independent of the global theme applied to the rest of the app. Additionally, the dark theme is further customized for the component by defining specific styles, such as the background color for the conversation container. This approach enables you to tailor the theme for specific components while maintaining the overall consistency of the global theme. +The following example shows how the theme for the `CometChatConversations` component is specifically overridden by wrapping it in a separate `CometChatThemeProvider`. This allows `CometChatConversations` to use a dark mode theme, independent of the global theme applied to the rest of the app. Additionally, the dark theme is further customized for the component by defining specific styles, such as the background color for the conversation container. This approach enables you to tailor the theme for specific components while maintaining the overall consistency of the global theme. @@ -181,6 +252,7 @@ import { useTheme, CometChatThemeProvider, } from "@cometchat/chat-uikit-react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; import Messages from "./src/Messages"; //other code @@ -245,7 +317,7 @@ return ( -When customizing theme properties, whether by overriding specific properties or supplying a completely custom theme, the provided values will be deeply merged with the default theme. This means that only the specified properties will be overridden, while all other properties will retain their default values. Additionally, if a style is passed through props, it will take priority over the style provided via the theme. The deep merge will occur in the following order of priority: +When customizing theme properties, whether by overriding specific properties or supplying a completely custom theme, the provided values will be deeply merged with the default theme. This means that only the specified properties will be overridden, while all other properties will retain their default values. Additionally, if a style is passed through props, it will take priority over the style provided via the theme. The deep merge occurs in the following order of priority: 1. The style prop (highest priority) 2. The custom theme @@ -265,3 +337,22 @@ const finalConversationsStyle = internalDeepMergeImplementation( ``` + +--- + +## Next Steps + + + + Customize primary, neutral, alert, and other color tokens + + + Style individual message bubbles and their content + + + Translate UI strings and support multiple languages + + + Explore all available UI Kit components + + diff --git a/ui-kit/react-native/threaded-messages-header.mdx b/ui-kit/react-native/threaded-messages-header.mdx index 14c2d1aa4..3c23eb273 100644 --- a/ui-kit/react-native/threaded-messages-header.mdx +++ b/ui-kit/react-native/threaded-messages-header.mdx @@ -1,94 +1,99 @@ --- title: "Threaded Messages Header" +description: "Display the parent message and reply count for threaded conversations with CometChatThreadHeader component in React Native UI Kit." --- -## Overview + +```json +{ + "component": "CometChatThreadHeader", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatThreadHeader } from \"@cometchat/chat-uikit-react-native\";", + "description": "Displays the parent message and number of replies in a thread.", + "props": { + "data": { + "parentMessage": { + "type": "CometChat.BaseMessage", + "note": "The parent message for which replies are shown" + }, + "template": { + "type": "CometChatMessageTemplate", + "note": "Custom template for the parent message bubble" + } + }, + "visibility": { + "replyCountVisibility": { "type": "boolean", "default": true }, + "replyCountBarVisibility": { "type": "boolean", "default": true }, + "receiptsVisibility": { "type": "boolean", "default": true }, + "avatarVisibility": { "type": "boolean", "default": true } + }, + "formatting": { + "alignment": { "type": "MessageBubbleAlignmentType", "default": "left" }, + "datePattern": "(message: CometChat.BaseMessage) => string", + "textFormatters": "Array" + } + } +} +``` + -`CometChatThreadHeader` is a [Component](/ui-kit/react-native/components-overview#components) that displays the parent message & number of replies of thread. +## Where It Fits + +`CometChatThreadHeader` is a [Component](/ui-kit/react-native/components-overview#components) that displays the parent message and number of replies in a thread. -## Usage - -### Integration +--- -The following code snippet illustrates how you can directly incorporate the `CometChatMessageList` component into your app. +## Minimal Render - - -```tsx +```tsx lines import { CometChatMessageList, CometChatThreadHeader, } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - <> - {!parentMessage && ( - { - // Set Parent Message - setParentMessage(message); - }} - /> - )} - {parentMessage && } - -); +import { useState } from "react"; + +function ThreadHeaderDemo() { + const [parentMessage, setParentMessage] = useState(null); + + return ( + <> + {!parentMessage && ( + { + setParentMessage(message); + }} + /> + )} + {parentMessage && } + + ); +} ``` - - - - -*** - -## Customization - -To fit your app's design requirements, you can customize the appearance of the conversation component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. - -*** - -### Style - -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +--- -### Thread Header +## Styling -The `CometChatThreadHeader` is used in threaded message views, displaying information about the parent message. It provides a seamless way to navigate between the thread and the main conversation. +Using Style you can customize the look and feel of the component in your app. Pass a styling object as a prop to the `CometChatThreadHeader` component. - - -```tsx -import { - CometChatMessageList, - CometChatThreadHeader, -} from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -return ( - <> - {!parentMessage && ( - { - // Set Parent Message - setParentMessage(message); - }} - /> - )} - {parentMessage && ( - - )} - -); + }} + /> + ); +} ``` - - - - -*** - -### Functionality - -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can change text, set custom icons, and toggle the visibility of UI elements. - -Below is a list of customizations along with corresponding code snippets +### Visibility Props -| Property | Description | Code | -| --------------------------- | ------------------------------------------------------------------- | ------------------------------- | -| **parentMessage** | Used to to set the message for which the replies need to be fetched | `parentMessage={messageObject}` | -| **template** | Used to to set custom template for the parent message | `template={templateObject}` | -| **replyCountVisibility** | Used to toggle reply count visibility | `replyCountVisibility={true}` | -| **replyCountBarVisibility** | Used to to toggle reply count bar visibility | `template={templateObject}` | -| **receiptsVisibility** | Used to to toggle receipts Visibility | `template={templateObject}` | -| **avatarVisibility** | Used to to toggle avatarVisibility | `template={templateObject}` | +| Property | Description | Code | +| --- | --- | --- | +| `replyCountVisibility` | Toggle reply count visibility | `replyCountVisibility?: boolean` | +| `replyCountBarVisibility` | Toggle reply count bar visibility | `replyCountBarVisibility?: boolean` | +| `receiptsVisibility` | Toggle receipts visibility | `receiptsVisibility?: boolean` | +| `avatarVisibility` | Toggle avatar visibility | `avatarVisibility?: boolean` | +| `alignment` | Alignment type for the parent message bubble | `alignment?: MessageBubbleAlignmentType` | -*** +### Custom Template -### Advanced +The `template` property is used to configure and set a custom template for parent message bubble. -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. - -#### Template - -The `template` property is used to configure and set a custom template for parent message bubble. It allows for dynamic customization of message appearance, content, or other predefined settings based on the template provided. - - - -```tsx +```tsx lines import { CometChat } from "@cometchat/chat-sdk-react-native"; import { - CometChatMessageList, - BorderStyleInterface, - AvatarStyleInterface, + CometChatThreadHeader, + CometChatMessageTemplate, + ChatConfigurator, + MessageBubbleAlignmentType, + useTheme, } from "@cometchat/chat-uikit-react-native"; -//code - -const getTemplate = () => { - //for example customizing text message template - let templates: CometChatMessageTemplate[] = - ChatConfigurator.getDataSource().getAllMessageTemplates(theme); - const textTemplate = templates.find((template) => { - if (template.type == "text") { - template.ContentView = ( - messageObject: CometChat.BaseMessage, - alignment: MessageBubbleAlignmentType - ) => { - const textMessage: CometChat.TextMessage = - messageObject as CometChat.TextMessage; - return ( - - {textMessage.getText()} - - ); - }; - return template; - } - }); - return textTemplate; -}; - -return ( - <> - {!parentMessage && ( - { - // Set Parent Message - setParentMessage(message); - }} - /> - )} - {parentMessage && ( - - )} - -); +import { Text } from "react-native"; + +function CustomTemplateDemo() { + const theme = useTheme(); + + const getTemplate = () => { + let templates: CometChatMessageTemplate[] = + ChatConfigurator.getDataSource().getAllMessageTemplates(theme); + const textTemplate = templates.find((template) => { + if (template.type == "text") { + template.ContentView = ( + messageObject: CometChat.BaseMessage, + alignment: MessageBubbleAlignmentType + ) => { + const textMessage = messageObject as CometChat.TextMessage; + return ( + + {textMessage.getText()} + + ); + }; + return template; + } + }); + return textTemplate; + }; + + return ( + + ); +} ``` - +--- - +## Next Steps + + + + Display the complete threaded conversation view + + + Display the list of messages in a conversation + + + Customize message bubble templates + + + Customize the appearance of UI Kit components + + diff --git a/ui-kit/react-native/upgrading-from-v4.mdx b/ui-kit/react-native/upgrading-from-v4.mdx index a7fac7e7d..aa86ff9d2 100644 --- a/ui-kit/react-native/upgrading-from-v4.mdx +++ b/ui-kit/react-native/upgrading-from-v4.mdx @@ -1,7 +1,20 @@ --- title: "Upgrading From V4" +description: "Migrate from CometChat React Native UI Kit v4 to v5 with updated components, simplified theming, and modular architecture." --- + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key changes | Composite components → modular components, `CometChatTheme` class → `CometChatThemeProvider`, nested styles → single `style` prop | +| View renames | `ListItemView` → `ItemView`, `TailView` → `TrailingView`, `EmptyStateView` → `EmptyView` | +| Property changes | [See below](#property-changes) | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/examples/SampleApp) | + + + ## Introduction @@ -53,12 +66,12 @@ The **v4** UI Kit provided composite components like `CometChatConversationsWith In **v5**, the composite approach is replaced with smaller, modular components like `Conversations`, `Message Header`, `Message List`, and `Message Composer`. Developers now need to stitch these components together to build the desired functionality. This change allows for greater flexibility and easier customization via props, significantly improving the developer experience while maintaining functionality. -| Components in v5 UI Kit: | | | -| ------------------------ | ------------------------------- | --------------------- | -| CometChatConversations | CometChatUsers | CometChatGroups | -| CometChatGroupMembers | CometChatMessageHeader | CometChatMessageList | -| CometChatMessageComposer | CometChatThreadedMessagePreview | CometChatIncomingCall | -| CometChatOutgoingCall | CometChatCallButtons | CometChatCallLogs | +| Components in v5 UI Kit: | | | +| ------------------------- | ---------------------------------- | -------------------------- | +| CometChatConversations | CometChatUsers | CometChatGroups | +| CometChatGroupMembers | CometChatMessageHeader | CometChatMessageList | +| CometChatMessageComposer | CometChatThreadHeader | CometChatIncomingCall | +| CometChatOutgoingCall | CometChatCallButtons | CometChatCallLogs | ## Theming @@ -109,7 +122,7 @@ The new theming system provides better flexibility for component-level styling t ```tsx App.tsx (v5) import React from "react"; -import { SafeAreaView } from "react-native"; +import { SafeAreaView } from "react-native-safe-area-context"; import { CometChatThemeProvider, CometChatI18nProvider } from "@cometchat/chat-uikit-react-native"; const customTheme = { @@ -176,4 +189,691 @@ Custom view properties have undergone a comprehensive overhaul to ensure consist This consistent naming convention makes it easier for developers to understand and apply customizations across various components, streamlining the development process. -For a comprehensive overview of newly added, renamed, and removed properties, refer to the [Property Changes](/ui-kit/react-native/property-changes) Documentation. \ No newline at end of file +For a comprehensive overview of newly added, renamed, and removed properties, refer to the [Property Changes](/ui-kit/react-native/property-changes) Documentation. + +--- + +## Next Steps + + + + Detailed reference of new, renamed, and removed props for each component + + + Set up the v5 UI Kit and send your first message + + + Customize colors, fonts, and styles with the new theme system + + + Style individual components using the simplified v5 approach + + +This consistent naming convention makes it easier for developers to understand and apply customizations across various components, streamlining the development process. + +--- + +## Property Changes + +In CometChat v5 UI Kit, several props and methods in components have been updated. Below is a detailed reference of renamed, added, and removed properties for each component. + +### Conversations + +#### New Properties +| Name | Type | Description | +| ------------------------- | ----------------------------- | ---------------------------------------------------------------------------------- | +| `hideSubmitButton` | boolean | Hide the submit (selection) button. | +| `receiptsVisibility` | boolean | Toggles message receipts (single/double-tick) inside the subtitle. | +| `disableSoundForMessages` | boolean | Toggle sound playback for received messages. | +| `customSoundForMessages` | string | Custom sound file path for received messages. | +| `datePattern` | `(conversation: CometChat.Conversation) => string` | Function to generate a custom date string for a conversation. | +| `ItemView` | `(item: CometChat.Conversation) => JSX.Element` | Completely overrides the default rendering of each conversation item in the list. | +| `AppBarOptions` | `() => JSX.Element` | Functional component for rendering options in the app bar. | +| `hideBackButton` | boolean | Hide the back button. | +| `selectionMode` | `'none' \| 'single' \| 'multiple'` | Selection mode: `'none'`, `'single'`, or `'multiple'`. | +| `onSelection` | `(conversations: Array) => void` | Callback when conversation selection is complete. | +| `onSubmit` | `(conversations: Array) => void` | Callback when submit selection button is pressed. | +| `EmptyView` | `() => JSX.Element` | Custom view for the empty state. | +| `ErrorView` | `() => JSX.Element` | Custom view for the error state. | +| `LoadingView` | `() => JSX.Element` | Custom view for the loading state. | +| `conversationsRequestBuilder` | `CometChat.ConversationsRequestBuilder` | Request builder to fetch conversations. | +| `LeadingView` | `(conversation: CometChat.Conversation) => JSX.Element` | Custom leading view for a conversation item. | +| `TitleView` | `(conversation: CometChat.Conversation) => JSX.Element` | Custom title view for a conversation item. | +| `SubtitleView` | `(conversation: CometChat.Conversation) => JSX.Element` | Custom subtitle view for a conversation item. | +| `TrailingView` | `(conversation: CometChat.Conversation) => JSX.Element` | Custom tail view for a conversation item. | +| `hideError` | boolean | Hide error view. | +| `onItemPress` | `(item: CometChat.Conversation) => void` | Callback for when a conversation item is pressed. | +| `onItemLongPress` | `(item: CometChat.Conversation) => void` | Callback for when a conversation item is long pressed. | +| `onError` | `(e: CometChat.CometChatException) => void` | Callback when an error occurs while fetching conversations. | +| `onBack` | `() => void` | Callback for when the back action is triggered. | +| `textFormatters` | `Array` | Array of text formatter classes. | +| `style` | `DeepPartial` | Custom styles for the conversation view. | +| `hideHeader` | boolean | Hide the header of the conversation list. | +| `onEmpty` | `() => void` | Callback triggered when the fetched list is empty. | +| `onLoad` | `(list: CometChat.Conversation[]) => void` | Callback triggered once the users have loaded and are not empty. | +| `options` | `(conversation: CometChat.Conversation) => MenuItemInterface[]` | A function to replace the default menu items entirely for a conversation. | +| `addOptions` | `(conversation: CometChat.Conversation) => MenuItemInterface[]` | A function to append more menu items on top of the default menu items for a conversation. | +| `usersStatusVisibility` | boolean | Toggle user status visibility. | +| `groupTypeVisibility` | boolean | Toggle group type visibility. | +| `deleteConversationOptionVisibility` | boolean | Toggle delete conversation option visibility. | + + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| `hideSubmitIcon` | `hideSubmitButton` | boolean | Hide the submit (selection) button. | +| `disableUsersPresence` | `usersStatusVisibility` | boolean | Toggle user status visibility. | +| `hideReceipt` / `disableReceipt` | `receiptsVisibility` | boolean | Controls receipt visibility. | +| `tailView` | `TrailingView` | function | Custom tail/trailing view for a conversation item. | +| `ListItemView` | `ItemView` | function | Completely overrides the default rendering of each conversation item in the list. | +| `AppBarOption` | `AppBarOptions` | function | Functional component for rendering options in the app bar. | +| `showBackButton` | `hideBackButton` | boolean | In v5, the prop is inverted (showBackButton=false → hideBackButton=true). | +| `conversationsStyle` | `style` | object | Style object for conversations (renamed and type changed). | +| `EmptyStateView` | `EmptyView` | function | Custom view for the empty state. | +| `ErrorStateView` | `ErrorView` | function | Custom view for the error state. | +| `LoadingStateView` | `LoadingView` | function | Custom view for the loading state. | + + +#### Removed Properties +| V4 Name | Type | Description | +| -------------------------- | ----------- | ------------------------------------------------------------------ | +| `protectedGroupIcon` | ImageType | Custom icon for protected group. | +| `privateGroupIcon` | ImageType | Custom icon for private group. | +| `readIcon` | ImageType | Custom icon for read message. | +| `deliveredIcon` | ImageType | Custom icon for delivered message. | +| `sentIcon` | ImageType | Custom icon for sent message. | +| `errorIcon` | ImageType | Custom icon for error message. | +| `waitingIcon` | ImageType | Custom icon for waiting message. | +| `options (swipe actions)` | function | Pass array of `CometChatOptions` type for swipe actions. | +| `hideSeparator` | boolean | Toggle separator. | +| `backButtonIcon` | ImageType | Icon for back button. | +| `title` | string | Title to be shown, default `"Chats"`. | +| `emptyStateText` | string | Text to be displayed if no conversation found. | +| `errorStateText` | string | Text to be displayed if there is an error. | +| `conversationsStyle (old type)` | object | (Renamed to `style`, but if old type, it's removed). | +| `listItemStyle` | object | Style object for list item. | +| `avatarStyle` | object | Style object for avatar. | +| `statusIndicatorStyle` | object | Style object for status indicator. | +| `dateStyle` | object | Style object for date. | +| `receiptStyle` | object | Style object for receipt. | +| `badgeStyle` | object | Style object for badge. | +| `confirmDialogStyle` | object | Style object for confirm dialog. | +| `disableTyping` | boolean | Toggle typing indicator. | +| `disableMentions` | boolean | If true, mentions will be disabled. | + + +### Users + +#### New Properties +| Name | Type | Description | +| ------------------------- | ----------------------------- | ---------------------------------------------------------------------------------- | +| `onSubmit` | `(list: Array) => void` | Callback when submit selection button is pressed. | +| `style` | `DeepPartial` | Custom styling for the users list. | +| `TitleView` | `(user: CometChat.User) => JSX.Element` | Custom title view component. | +| `ItemView` | `(user: CometChat.User) => JSX.Element` | Function that returns a custom list item view. | +| `EmptyView` | `() => JSX.Element` | Custom component to display for the empty state. | +| `ErrorView` | `() => JSX.Element` | Custom component to display for the error state. | +| `LoadingView` | `() => JSX.Element` | Custom component to display for the loading state. | +| `LeadingView` | `(user: CometChat.User) => JSX.Element` | Custom leading view component. | +| `hideHeader` | boolean | Hide the header view. | +| `searchPlaceholderText` | string | Placeholder text for the search input. | +| `usersStatusVisibility` | boolean | Hide the users status. | +| `searchKeyword` | string | Search keyword. | +| `onError` | `(e: CometChat.CometChatException) => void` | Callback when an error occurs. | +| `hideLoadingState` | boolean | Hide the loading skeleton. | +| `title` | string | Title for the header. | +| `addOptions` | `(user: CometChat.User) => MenuItemInterface[]` | A function to append more menu items on top of the default menu items for a user. | +| `hideError` | boolean | Toggle error view visibility. | +| `showBackButton` | boolean | Toggle back button visibility. | +| `stickyHeaderVisibility` | boolean | Toggle sticky header visibility. | + + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| --------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| `usersStyle` | `style` | object | Custom styling for the users list. | +| `TailView` | `TrailingView` | function | Function that returns a custom trailing view for a user. | +| `disableUsersPresence` | `usersStatusVisibility` | boolean | Toggle user status visibility| +| `ListItemView` | `ItemView` | function | Function that returns a custom list item view. | + + +#### Removed Properties +| V4 Name | Type | Description | +| --------------------- | ------------ | ---------------------------------------------------------------------------------- | +| `listItemKey` | any | Key for list item *(removed in v5)*. | + + +### Groups + +#### New Properties +| Name | Type | Description | +| ------------------------- | ----------------------------- | ---------------------------------------------------------------------------------- | +| `TitleView` | `(group: CometChat.Group) => JSX.Element` | Custom title view for a group item. | +| `SubtitleView` | `(group: CometChat.Group) => JSX.Element` | Custom subtitle view for a group item. | +| `TrailingView` | `(group: CometChat.Group) => JSX.Element` | Custom trailing view for a group item. | +| `ItemView` | `(group: CometChat.Group) => JSX.Element` | Completely overrides the default rendering of each group item in the list. | +| `AppBarOptions` | `() => JSX.Element` | Functional component for rendering options in the app bar. | +| `hideSubmitButton` | boolean | Hide the submit (selection) button. | +| `style` | `DeepPartial` | Custom styles for the groups view. | +| `searchPlaceholderText` | string | Placeholder text for the search input. | +| `selectionMode` | `'none' \| 'single' \| 'multiple'` | Selection mode: `'none'`, `'single'`, or `'multiple'`. | +| `onSelection` | `(list: Array) => void` | Callback when group selection is complete. | +| `onSubmit` | `(list: Array) => void` | Callback when submit selection button is pressed. | +| `hideSearch` | boolean | Hide the search box. | +| `EmptyView` | `() => JSX.Element` | Custom view for the empty state. | +| `ErrorView` | `() => JSX.Element` | Custom view for the error state. | +| `LoadingView` | `() => JSX.Element` | Custom view for the loading state. | +| `groupsRequestBuilder` | `CometChat.GroupsRequestBuilder` | Request builder to fetch groups. | +| `searchRequestBuilder` | `CometChat.GroupsRequestBuilder` | Request builder for search functionality. | +| `privateGroupIcon` | `ImageSourcePropType` | Icon to be used for private groups. | +| `passwordGroupIcon` | `ImageSourcePropType` | Icon to be used for password-protected groups. | +| `hideError` | boolean | Hide error view. | +| `onItemPress` | `(item: CometChat.Group) => void` | Callback for when a group item is pressed. | +| `onItemLongPress` | `(item: CometChat.Group) => void` | Callback for when a group item is long pressed. | +| `onError` | `(e: CometChat.CometChatException) => void` | Callback when an error occurs while fetching groups. | +| `onBack` | `() => void` | Callback for when the back action is triggered. | +| `hideHeader` | boolean | Hide the header of the group list. | +| `LeadingView` | `(group: CometChat.Group) => JSX.Element` | Custom leading view for a group item. | +| `searchKeyword` | string | Search keyword. | +| `onEmpty` | `() => void` | Callback triggered when the fetched list is empty. | +| `onLoad` | `(list: CometChat.GroupMember[]) => void` | Callback triggered once the groups have loaded and are not empty. | +| `hideLoadingState` | boolean | Hide the loading skeleton. | +| `groupTypeVisibility` | boolean | Hide the group type *(public/private/password)*. | +| `addOptions` | `(group: CometChat.Group) => MenuItemInterface[]` | A function to append more menu items on top of the default menu items for a group. | +| `options` | `(group: CometChat.Group) => MenuItemInterface[]` | A function to replace the default menu items entirely for a group. | + + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| `ListItemView` | `ItemView` | function | Completely overrides the default rendering of each group item in the list. | +| `AppBarOption` | `AppBarOptions` | function | Functional component for rendering options in the app bar. | +| `hideSubmitIcon` | `hideSubmitButton` | boolean | Hide the submit (selection) button. | +| `groupsStyle` | `style` | object | Style object for groups *(renamed and type changed)*. | +| `searchPlaceHolderText` | `searchPlaceholderText` | string | Placeholder text for the search input. | +| `EmptyStateView` | `EmptyView` | function | Custom view for the empty state. | +| `ErrorStateView` | `ErrorView` | function | Custom view for the error state. | +| `LoadingStateView` | `LoadingView` | function | Custom view for the loading state. | +| `privateGroupIcon` | `privateGroupIcon` | `ImageType` → `ImageSourcePropType` | Icon to be used for private groups *(type changed)*. | +| `passwordGroupIcon` | `passwordGroupIcon` | `ImageType` → `ImageSourcePropType` | Icon to be used for password-protected groups *(type changed)*. | + + +#### Removed Properties +| V4 Name | Type | Description | +| ------------------------- | ------------ | ---------------------------------------------------------------------------------- | +| `hideSeperator` | boolean | Toggle separator *(removed, not present in v5)*. | +| `listItemStyle` | object | Style object for list item *(removed, not present in v5)*. | +| `avatarStyle` | object | Style object for avatar *(removed, not present in v5)*. | +| `statusIndicatorStyle` | object | Style object for status indicator *(removed, not present in v5)*. | +| `backButtonIcon` | ImageType | Icon for back button *(removed, not present in v5)*. | +| `searchBoxIcon` | ImageType | Icon for search box *(removed, not present in v5)*. | +| `title` | string | Title to be shown, default `"Groups"` *(removed, not present in v5)*. | +| `emptyStateText` | string | Text to be displayed if no group found *(removed, not present in v5)*. | +| `errorStateText` | string | Text to be displayed if there is an error *(removed, not present in v5)*. | + + +### Group Members + +#### New Properties +| Name | Type | Description | +| ------------------------- | ----------------------------- | ---------------------------------------------------------------------------------- | +| `SubtitleView` | `(item: CometChat.GroupMember) => JSX.Element` | Custom subtitle view for a group member item. | +| `TitleView` | `(item: CometChat.GroupMember) => JSX.Element` | Custom title view for a group member item. | +| `TrailingView` | `(item: CometChat.GroupMember) => JSX.Element` | Custom trailing view for a group member item. | +| `EmptyView` | `() => JSX.Element` | Custom view for the empty state. | +| `ErrorView` | `() => JSX.Element` | Custom view for the error state. | +| `LoadingView` | `() => JSX.Element` | Custom view for the loading state. | +| `onItemPress` | `(groupMember: CometChat.GroupMember) => void` | Callback when a group member item is pressed. | +| `onItemLongPress` | `(groupMember: CometChat.GroupMember) => void` | Callback when a group member item is long pressed. | +| `onSelection` | `(list: CometChat.GroupMember[]) => void` | Callback when group member selection is complete. | +| `onSubmit` | `(list: Array) => void` | Callback when submit selection button is pressed. | +| `searchRequestBuilder` | `CometChat.GroupMembersRequestBuilder` | Request builder for search functionality. | +| `groupMemberRequestBuilder` | `CometChat.GroupMembersRequestBuilder` | Request builder to fetch group members. | +| `group` | `CometChat.Group` | The group object for which members are listed. | +| `style` | `DeepPartial` | Custom styles for the group member view. | +| `ItemView` | `(item: CometChat.GroupMember) => JSX.Element` | Completely overrides the default rendering of each group member item. | +| `LeadingView` | `(item: CometChat.GroupMember) => JSX.Element` | Custom leading view for a group member item. | +| `onEmpty` | `() => void` | Callback triggered when the fetched list is empty. | +| `onLoad` | `(list: CometChat.GroupMember[]) => void` | Callback triggered once the group members have loaded and are not empty. | +| `options` | `(member: CometChat.GroupMember, group: CometChat.Group) => MenuItemInterface[]` | Function to replace default menu items entirely for a group member. | +| `addOptions` | `(member: CometChat.GroupMember, group: CometChat.Group) => MenuItemInterface[]` | Function to append more menu items on top of default menu items for a group member. | +| `hideKickMemberOption` | `boolean` | Hide the "Remove" (Kick) option from the default menu. | +| `hideBanMemberOption` | `boolean` | Hide the "Ban" option from the default menu. | +| `hideScopeChangeOption` | `boolean` | Hide the "Change Scope" option from the default menu. | +| `hideLoadingState` | `boolean` | Hide the loading skeleton. | +| `usersStatusVisibility` | `boolean` | Toggle user status visibility. | +| `hideHeader` | `boolean` | Hide the header view. | +| `onError` | `() => void` | Callback when an error occurs. | +| `searchKeyword` | `string` | Search keyword. | +| `showBackButton` | `boolean` | Toggle back button visibility. | +| `excludeOwner` | `boolean` | Exclude owner from the list. | + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| `TailView` | `TrailingView` | function | Custom trailing view for a group member item. | +| `groupMemberStyle` | `style` | object | Style object for group member (renamed and type changed). | +| `disableUsersPresence` | `usersStatusVisibility` | boolean | Toggle user status visibility | +| `ListItemView` | `ItemView` | function | Completely overrides the default rendering of each group member item. | +| `EmptyStateView` | `EmptyView` | function | Custom view for the empty state. | +| `ErrorStateView` | `ErrorView` | function | Custom view for the error state. | +| `LoadingStateView` | `LoadingView` | function | Custom view for the loading state. | + +#### Removed Properties +| V4 Name | Type | Description | +| ------------------------- | ------------ | ---------------------------------------------------------------------------------- | +| `listItemStyle` | object | Style object for list item *(removed in v5)*. | +| `avatarStyle` | object | Style object for avatar *(removed in v5)*. | +| `statusIndicatorStyle` | object | Style object for status indicator *(removed in v5)*. | +| `groupScopeStyle` | object | Styling properties for group scope *(removed in v5)*. | +| `title` | string | Title for the list *(removed in v5)*. | +| `errorStateText` | string | Text to be displayed when error occurs *(removed in v5)*. | +| `emptyStateText` | string | Text to be displayed when the list is empty *(removed in v5)*. | +| `theme` | `CometChatTheme` | Theme configuration for the group members component *(removed in v5)*. | + + +### Message Header + +#### New Properties +| Name | Type | Description | +| ------------------------- | ----------------------------- | ---------------------------------------------------------------------------------- | +| `ItemView` | `({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element` | Custom item view. Receives `{ user, group }`. | +| `LeadingView` | `({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element` | Custom leading view. Receives `{ user, group }`. | +| `TitleView` | `({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element` | Custom title view. Receives `{ user, group }`. | +| `SubtitleView` | `({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element` | Custom subtitle view. Receives `{ user, group }`. | +| `TrailingView` | `({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element` | Custom trailing view. Receives `{ user, group }`. | +| `AuxiliaryButtonView` | `({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element` | Custom auxiliary button view. Receives `{ user, group }`. | +| `user` | `CometChat.User` | User object. | +| `group` | `CometChat.Group` | Group object. | +| `showBackButton` | `boolean` | Toggle back button visibility. | +| `onBack` | `() => void` | Callback when back button is pressed. | +| `style` | `DeepPartial` | Custom styles. | +| `onError` | `(error: CometChat.CometChatException) => void` | Error callback. | +| `hideVoiceCallButton` | `boolean` | Toggle visibility of voice call button. | +| `hideVideoCallButton` | `boolean` | Toggle visibility of video call button. | +| `usersStatusVisibility` | `boolean` | Toggle visibility of user status. | +| `hideNewChatButton` | `boolean` | Flag to hide the new chat button for AI agents (only applies to @agentic users). | +| `hideChatHistoryButton` | `boolean` | Flag to hide the chat history button for AI agents (only applies to @agentic users). | +| `onNewChatButtonClick` | `() => void` | Callback when agent new chat button is clicked (only applies to @agentic users). | +| `onChatHistoryButtonClick` | `() => void` | Callback when agent chat history button is clicked (only applies to @agentic users). | + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +| ------------------------- | -------------- | -------------- | ---------------------------------------------------------------------------------- | +| `ListItemView` | `ItemView` | function | Custom item view. | +| `AppBarOptions` | `TrailingView` | function | Custom trailing view. | +| `hideBackIcon` | `showBackButton` | boolean | In v5, the prop is inverted (hideBackIcon=true → showBackButton=false). | +| `disableUsersPresence` | `usersStatusVisibility` | boolean | Toggle user status visibility | +| `style` | `style` | object | Style object for message header (renamed and type changed). | + +#### Removed Properties +| V4 Name | Type | Description | +| ------------------------- | ------------ | ---------------------------------------------------------------------------------- | +| `protectedGroupIcon` | `ImageType` | Custom icon for protected group *(removed in v5)*. | +| `privateGroupIcon` | `ImageType` | Custom icon for private group *(removed in v5)*. | +| `backButtonIcon` | `ImageType` | Icon for back button *(removed in v5)*. | +| `disableTyping` | `boolean` | Controls typing indicator functionality *(removed in v5)*. | +| `avatarStyle` | `object` | Style configuration for avatar *(removed in v5)*. | +| `statusIndicatorStyle` | `object` | Style configuration for status indicator *(removed in v5)*. | +| `headViewContainerStyle` | `object` | Custom styling for headViewContainer in list item *(removed in v5)*. | +| `bodyViewContainerStyle` | `object` | Custom styling for bodyViewContainerStyle in list item *(removed in v5)*. | +| `tailViewContainerStyle` | `object` | Custom styling for tailViewContainerStyle in list item *(removed in v5)*. | +| `listItemStyle` | `object` | Custom styling for list item *(removed in v5)*. | + + +### Message List + +#### New Properties +| Name | Type | Description | +|-------------|---------------------|---------------| +| `parentMessageId` | `string` | ID of the parent message when rendering threaded messages. | +| `user` | `CometChat.User` | The user object associated with the message list. | +| `group` | `CometChat.Group` | The group object associated with the message list. | +| `EmptyView` | `() => JSX.Element` | A component to display when there are no messages. | +| `ErrorView` | `() => JSX.Element` | A component to display when an error occurs. | +| `hideError` | `boolean` | Flag to hide the error view. | +| `LoadingView` | `() => JSX.Element` | A component to display while messages are loading. | +| `receiptsVisibility` | `boolean` | Flag to hide read receipts. | +| `disableSoundForMessages` | `boolean` | Flag to disable sound for incoming messages. | +| `customSoundForMessages` | `string` | Custom sound URL for messages. | +| `alignment` | `MessageListAlignmentType` | Alignment type for the message list. | +| `avatarVisibility` | `boolean` | Flag to show or hide the user's avatar. | +| `datePattern` | `(message: CometChat.BaseMessage) => string` | Function that returns a custom string representation for a message's date. | +| `dateSeparatorPattern` | `(date: number) => string` | Function that returns a custom date separator string based on a timestamp. | +| `templates` | `Array` | An array of message templates for rendering custom message types. | +| `addTemplates` | `Array` | An array of message templates for rendering custom message types. | +| `messageRequestBuilder` | `CometChat.MessagesRequestBuilder` | Builder for constructing a request to fetch messages. | +| `scrollToBottomOnNewMessages` | `boolean` | If true, the message list will scroll to the bottom when new messages arrive. | +| `onThreadRepliesPress` | `(messageObject: CometChat.BaseMessage, messageBubbleView: () => JSX.Element \| null) => void` | Callback invoked when the thread replies view is pressed. | +| `HeaderView` | `({ user, group, id }: { user?: CometChat.User; group?: CometChat.Group; id?: { uid?: string; guid?: string; parentMessageId?: string } }) => JSX.Element` | Custom header view component. | +| `FooterView` | `({ user, group, id }: { user?: CometChat.User; group?: CometChat.Group; id?: { uid?: string; guid?: string; parentMessageId?: string } }) => JSX.Element` | Custom footer view component. | +| `onError` | `(e: CometChat.CometChatException) => void` | Callback to handle errors. | +| `onBack` | `() => void` | Callback invoked on back navigation. | +| `textFormatters` | `Array` | Collection of text formatter classes to apply custom formatting. | +| `onReactionPress` | `(reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void` | Callback invoked when a reaction is pressed. | +| `onReactionLongPress` | `(reaction: CometChat.ReactionCount, messageObject: CometChat.BaseMessage) => void` | Callback invoked when a reaction is long pressed. | +| `onReactionListItemPress` | `(messageReaction: CometChat.Reaction, messageObject: CometChat.BaseMessage) => void` | Callback invoked when an item in the reaction list is pressed. | +| `style` | `DeepPartial` | Custom styles for the message list component. | +| `reactionsRequestBuilder` | `CometChat.ReactionsRequestBuilder` | Builder for constructing a request to fetch reactions. | +| `onAddReactionPress` | `() => void` | Callback invoked when the add reaction button is pressed. | +| `quickReactionList` | `[string, string?, string?, string?, string?]` | List of quick reactions. | +| `onLoad` | `(messageList: CometChat.BaseMessage[]) => void` | Callback to handle when the message list is loaded. | +| `onEmpty` | `() => void` | Callback to handle when the message list is empty. | +| `hideReplyInThreadOption` | `boolean` | Flag to hide the reply in thread option. | +| `hideShareMessageOption` | `boolean` | Flag to hide the share message option. | +| `hideEditMessageOption` | `boolean` | Flag to hide the edit message option. | +| `hideTranslateMessageOption` | `boolean` | Flag to hide the translate message option. | +| `hideDeleteMessageOption` | `boolean` | Flag to hide the delete message option. | +| `hideReactionOption` | `boolean` | Flag to hide the react to message option. | +| `hideMessagePrivatelyOption` | `boolean` | Flag to hide the message privately option. | +| `hideCopyMessageOption` | `boolean` | Flag to hide the copy message option. | +| `hideMessageInfoOption` | `boolean` | Flag to hide the message info option. | +| `hideGroupActionMessages` | `boolean` | Flag to hide group action messages. | +| `hideTimestamp` | `boolean` | Flag to hide the timestamp on message bubbles. | +| `suggestedMessages` | `Array` | Array of suggested messages for AI agent empty view (only applies to @agentic users). | +| `hideSuggestedMessages` | `boolean` | Flag to hide suggested messages in AI agent empty view (only applies to @agentic users). | +| `emptyChatGreetingView` | `React.ReactNode` | Custom AI agent greeting view (only applies to @agentic users). | +| `emptyChatIntroMessageView` | `React.ReactNode` | Custom AI agent intro message view (only applies to @agentic users). | +| `emptyChatImageView` | `React.ReactNode` | Custom AI agent image/avatar view (only applies to @agentic users). | +| `onSuggestedMessageClick` | `(suggestion: string) => void` | Callback when suggested message is clicked (only applies to @agentic users). | +| `aiAssistantTools` | `CometChatAIAssistantTools` | Custom AI assistant tools with action functions (only applies to @agentic users). | +| `streamingSpeed` | `number` | Controls the speed of AI message streaming (only applies to @agentic users). | + + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +|--------------------------|---------------------|-------------------------------|----------------------------------------------------------------------------------| +| `EmptyStateView` | `EmptyView` | `() => JSX.Element` | Custom component to display for the empty state. | +| `ErrorStateView` | `ErrorView` | `() => JSX.Element` | Custom component to display for the error state. | +| `LoadingStateView` | `LoadingView` | `() => JSX.Element` | Custom component to display for the loading state. | +| `hideReceipt` / `disableReceipt` | `receiptsVisibility` | `boolean` | Controls receipt visibility. | +| `showAvatar` | `avatarVisibility` | `boolean` | Toggle visibility for avatar. | +| `dateSeparatorPattern` | `dateSeparatorPattern` | `(date: number) => string` | Signature clarified with parameter name. | + +#### Removed Properties +| V4 Name | Type | Description | +|--------------------------|--------------------------|----------------------------------------------------------------------------------| +| `emptyStateText` | `string` | Text to be displayed if no message found. | +| `errorStateText` | `string` | Text to be displayed if there is an error. | +| `readIcon` | `ImageType` | Custom icon for read message. | +| `deliveredIcon` | `ImageType` | Custom icon for delivered message. | +| `sentIcon` | `ImageType` | Custom icon for sent message. | +| `waitIcon` | `ImageType` | Custom icon for waiting message. | +| `errorIcon` | `ImageType` | Custom icon for error message. | +| `wrapperMessageBubbleStyle` | `MessageBubbleStyleInterface` | Style for message bubble wrapper. | +| `avatarStyle` | `AvatarStyleInterface` | Style configuration for avatar. | +| `dateSeperatorStyle` | `DateStyleInterface` | Style for date separator. | +| `actionSheetStyle` | `ActionSheetStylesInterface` | Style for action sheet. | +| `messageListStyle` | `MessageListStyleInterface` | Style configuration for message list. | +| `messageInformationConfiguration` | `CometChatMessageInformationConfigurationInterface` | Configuration for message information. | +| `reactionsConfiguration` | `ReactionsConfigurationInterface` | Message Reaction Configuration. | +| `reactionListConfiguration` | `ReactionListConfigurationInterface` | Message Reaction List Configuration. | +| `quickReactionConfiguration` | `QuickReactionsConfigurationInterface` | Quick Reaction Configuration. | +| `emojiKeyboardStyle` | `EmojiKeyboardStyle` | Emoji Keyboard style. | +| `disableReactions` | `boolean` | Disables the reactions functionality. | +| `disableMentions` | `boolean` | Disables mentions functionality. | +| `timeStampAlignment` | `MessageTimeAlignmentType` | Alignment for message timestamps. | +| `newMessageIndicatorText` | `string` | Custom text for new message indicator. | +| `hideActionSheetHeader` | `boolean` | Hide the header of the action sheet. | + + +### Message Composer + +#### New Properties +| Name | Type | Description | +|--------------------------|-----------------------------|----------------------------------------------------------------------------------| +| `id` | `string \| number` | Message composer identifier. | +| `user` | `CometChat.User` | CometChat SDK's user object. | +| `group` | `CometChat.Group` | CometChat SDK's group object. | +| `disableSoundForOutgoingMessages` | `boolean` | Flag to turn off sound for outgoing messages. | +| `customSoundForOutgoingMessage` | `any` | Custom audio sound to be played while sending messages. | +| `disableTypingEvents` | `boolean` | Flag to disable typing events. | +| `initialComposertext` | `string` | Initial text to be displayed in the composer. | +| `HeaderView` | `({ user, group }: { user?: CometChat.User; group?: CometChat.Group }) => JSX.Element` | Renders a preview section at the top of the composer. | +| `onTextChange` | `(text: string) => void` | Callback triggered when the input text changes. | +| `attachmentOptions` | `({ user, group, composerId }: { user?: CometChat.User; group?: CometChat.Group; composerId: Map; }) => CometChatMessageComposerAction[]` | Returns the attachment options for the composer. | +| `AuxiliaryButtonView` | `({ user, group, composerId }: { user?: CometChat.User; group?: CometChat.Group; composerId: string \| number; }) => JSX.Element` | Replaces the default Auxiliary Button. | +| `SendButtonView` | `({ user, group, composerId }: { user?: CometChat.User; group?: CometChat.Group; composerId: string \| number; }) => JSX.Element` | Replaces the default Send Button. | +| `parentMessageId` | `string \| number` | Message id required for threaded messages. | +| `style` | `DeepPartial` | Custom styles for the message composer component. | +| `hideVoiceRecordingButton` | `boolean` | Flag to hide the voice recording button. | +| `onSendButtonPress` | `(message: CometChat.BaseMessage) => void` | Callback triggered when the send button is pressed. | +| `onError` | `(error: CometChat.CometChatException) => void` | Callback triggered when an error occurs. | +| `keyboardAvoidingViewProps` | `KeyboardAvoidingViewProps` | Override properties for the KeyboardAvoidingView. | +| `textFormatters` | `Array` | Collection of text formatter classes to apply custom formatting. | +| `disableMentions` | `boolean` | Flag to disable mention functionality. | +| `imageQuality` | `IntRange<1, 100>` | Controls image quality when taking pictures from the camera. | +| `hideCameraOption` | `boolean` | If true, hides the camera option from the attachment options. | +| `hideImageAttachmentOption` | `boolean` | If true, hides the image attachment option from the attachment options. | +| `hideVideoAttachmentOption` | `boolean` | If true, hides the video attachment option from the attachment options. | +| `hideAudioAttachmentOption` | `boolean` | If true, hides the audio attachment option from the attachment options. | +| `hideFileAttachmentOption` | `boolean` | If true, hides the file/document attachment option from the attachment options. | +| `hidePollsAttachmentOption` | `boolean` | If true, hides the polls option from the attachment options. | +| `hideCollaborativeDocumentOption` | `boolean` | If true, hides the collaborative document option. | +| `hideCollaborativeWhiteboardOption` | `boolean` | If true, hides the collaborative whiteboard option. | +| `hideAttachmentButton` | `boolean` | If true, hides the entire attachment button from the composer. | +| `hideStickersButton` | `boolean` | If true, hides the stickers button from the composer. | +| `hideSendButton` | `boolean` | If true, hides the send button from the composer. | +| `hideAuxiliaryButtons` | `boolean` | If true, hides all auxiliary buttons (such as voice input, GIFs, or other plugin buttons). | +| `addAttachmentOptions` | `({ user, group, composerId }: { user?: CometChat.User; group?: CometChat.Group; composerId: Map; }) => CometChatMessageComposerAction[]` | Returns additional attachment options for the composer. | +| `auxiliaryButtonsAlignment` | `"left" \| "right"` | Determines the alignment of auxiliary buttons. | + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +|--------------------------|---------------------|-------------------------------|----------------------------------------------------------------------------------| +| `disableSoundForMessages` | `disableSoundForOutgoingMessages` | `boolean` | Renamed for clarity. | +| `customSoundForMessage` | `customSoundForOutgoingMessage` | `any` | Renamed for clarity. | +| `text` | `initialComposertext` | `string` | Renamed for clarity. | +| `onChangeText` | `onTextChange` | `(text: string) => void` | Renamed for clarity. | +| `hideVoiceRecording` | `hideVoiceRecordingButton` | `boolean` | Renamed for clarity. | +| `attachmentOptions` | `attachmentOptions` | function signature changed | Function signature updated. | +| `SecondaryButtonView` | `AuxiliaryButtonView` | function signature changed | Function signature updated and renamed. | + +#### Removed Properties +| V4 Name | Type | Description | +|--------------------------|--------------------------|----------------------------------------------------------------------------------| +| `FooterView` | `React.FC` | Preview section at the bottom of the composer. | +| `placeHolderText` | `string` | Text shown in the composer when the input message is empty. | +| `maxHeight` | `number` | Threshold value for input expansion. | +| `attachmentIcon` | `ImageType` | Attachment icon. | +| `messageComposerStyle` | `MessageComposerStyleInterface` | Message Composer Styles. | +| `hideLiveReaction` | `boolean` | Hide the live reaction button. | +| `liveReactionIcon` | `ImageType` | Live reaction icon. | +| `voiceRecordingIconURL` | `string \| ImageType` | Image URL for the voice recording icon. | +| `mediaRecorderStyle` | `MediaRecorderStyle` | Voice Recording Styles. | +| `pauseIconUrl` | `ImageType` | Pause icon. | +| `playIconUrl` | `ImageType` | Play icon. | +| `recordIconUrl` | `ImageType` | Record icon. | +| `deleteIconUrl` | `ImageType` | Delete icon. | +| `stopIconUrl` | `ImageType` | Stop icon. | +| `submitIconUrl` | `ImageType` | Submit icon. | +| `AIIconURL` | `string` | AI Icon URL. | +| `aiOptionsStyle` | `AIOptionsStyle` | AI Options Style. | + + +### Incoming Call + +#### New Properties +| Name | Type | Description | +|--------------------------|-----------------------------|----------------------------------------------------------------------------------| +| `call` | `CometChat.Call \| CometChat.CustomMessage \| any` | The incoming call object, which can be a Call or a CustomMessage. | +| `ItemView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the entire call item. | +| `TitleView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the title section of the call item. | +| `SubtitleView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the subtitle section of the call item. | +| `LeadingView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the leading section of the call item. | +| `TrailingView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the trailing section of the call item. | +| `disableSoundForCalls` | `boolean` | Flag to disable sound for incoming calls. | +| `customSoundForCalls` | `string` | Path or identifier for a custom sound to play for incoming calls. | +| `onAccept` | `(message: CometChat.BaseMessage) => void` | Callback fired when the call is accepted. | +| `onDecline` | `(message: CometChat.BaseMessage) => void` | Callback fired when the call is declined. | +| `onError` | `(e: CometChat.CometChatException) => void` | Callback fired when an error occurs. | +| `callSettingsBuilder` | `typeof CometChatCalls.CallSettingsBuilder` | Optional custom call settings builder. | +| `style` | `DeepPartial` | Custom style overrides for the incoming call component. | + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +|--------------------------|---------------------|-------------------------------|----------------------------------------------------------------------------------| +| `SubtitleView` | `SubtitleView` | function signature changed | Function signature updated. | +| `incomingCallStyle` | `style` | `IncomingCallStyleInterface` → `DeepPartial` | Style object for incoming call (renamed and type changed). | +| `onAccept` | `onAccept` | function signature changed | Function signature updated. | +| `onDecline` | `onDecline` | function signature changed | Function signature updated. | + +#### Removed Properties +| V4 Name | Type | Description | +|--------------------------|--------------------------|----------------------------------------------------------------------------------| +| `title` | `string` | Custom title text. | +| `acceptButtonText` | `string` | Accept button text. | +| `declineButtonText` | `string` | Decline button text. | +| `avatarStyle` | `AvatarStyleInterface` | Style configuration for avatar. | +| `ongoingCallScreenStyle` | `OngoingCallStyleInterface` | Style for ongoing call screen. | + + +### Outgoing Call + +#### New Properties +| Name | Type | Description | +|--------------------------|-----------------------------|----------------------------------------------------------------------------------| +| `onEndCallButtonPressed` | `(call: CometChat.Call) => void` | Callback for when the end/cancel button is pressed. | +| `EndCallView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the end call button. | +| `TitleView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the title section. | +| `SubtitleView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the subtitle section. | +| `AvatarView` | `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Custom view for the avatar section. | + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +|--------------------------|---------------------|-------------------------------|----------------------------------------------------------------------------------| +| `onDeclineButtonPressed` | `onEndCallButtonPressed` | `(call: CometChat.Call) => void` | Renamed for clarity and consistency. | +| `declineButtonIcon` | `EndCallView` | `ImageType` → `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Changed from icon/image to custom view. | +| `declineButtonText` | `EndCallView` | `string` → `(call: CometChat.Call \| CometChat.CustomMessage) => JSX.Element` | Changed from text to custom view. | +| `outgoingCallStyle` | `style` | `OutgoingCallStyleInterface` → `DeepPartial` | Style object renamed and type changed. | + +#### Removed Properties +| V4 Name | Type | Description | +|--------------------------|--------------------------|----------------------------------------------------------------------------------| +| `buttonStyle` | `ButtonStyleInterface` | Style object for button (removed, not present in v5). | +| `avatarStyle` | `AvatarStyleInterface` | Style object for avatar (removed, not present in v5). | +| `declineButtonText` | `string` | Decline button text (replaced by `EndCallView`). | +| `declineButtonIcon` | `ImageType` | Decline button icon (replaced by `EndCallView`). | +| `onDeclineButtonPressed` | `(call: CometChat.Call) => void` | Callback (renamed to `onEndCallButtonPressed`). | +| `outgoingCallStyle` | `OutgoingCallStyleInterface` | Style object (renamed to `style`). | +| `callSettingsBuilder` | `typeof CometChatCalls.CallSettingsBuilder` | (Moved to new properties, type clarified). | +| `theme` | `CometChatTheme` | Theme configuration (removed, not present in v5). | +| `cardStyle` | `CardStyleInterface` | Card style (removed, not present in v5). | +| `ongoingCallConfiguration` | `OngoingCallConfigurationInterface` | Ongoing call config (removed, not present in v5). | + + +### Call Buttons + +#### New Properties +| Name | Type | Description | +|--------------------------|-----------------------------|----------------------------------------------------------------------------------| +| `callSettingsBuilder` | `(user?: CometChat.User, group?: CometChat.Group, isAudioOnly?: boolean) => typeof CometChatCalls.CallSettingsBuilder` | Function to build call settings for call initialization. | +| `outgoingCallConfiguration` | `OutgoingCallConfiguration` | Configuration for outgoing calls. | +| `style` | `DeepPartial` | Custom style overrides for the call button. | + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +|--------------------------|---------------------|-------------------------------|----------------------------------------------------------------------------------| +| `hideVoiceCall` | `hideVoiceCallButton` | `boolean` | Renamed for clarity. | +| `hideVideoCall` | `hideVideoCallButton` | `boolean` | Renamed for clarity. | +| `callButtonStyle` | `style` | `CallButtonStyleInterface` → `DeepPartial` | Style object renamed and type changed. | + +#### Removed Properties +| V4 Name | Type | Description | +|--------------------------|--------------------------|----------------------------------------------------------------------------------| +| `voiceCallIconImage` | `ImageType` | Image icon for voice calls. | +| `voiceCallIconText` | `string` | Text label for the voice call icon. | +| `videoCallIconImage` | `ImageType` | Image icon for video calls. | +| `videoCallIconText` | `string` | Text label for the video call icon. | +| `onVoiceCallPress` | `(params: { user?: CometChat.User, group?: CometChat.Group }) => void` | Callback for voice call icon click. | +| `onVideoCallPress` | `(params: { user?: CometChat.User, group?: CometChat.Group }) => void` | Callback for video call icon click. | +| `callButtonStyle` | `CallButtonStyleInterface` | Style object (renamed to `style`). | + + +### Call Logs + +#### New Properties +| Name | Type | Description | +|--------------------------|-----------------------------|----------------------------------------------------------------------------------| +| `LeadingView` | `(call?: any) => JSX.Element` | Custom component for the leading view of each call log item. | +| `TitleView` | `(call?: any) => JSX.Element` | Custom component for the title view of each call log item. | +| `SubtitleView` | `(call?: any) => JSX.Element` | Custom component for the subtitle view of each call log item. | +| `ItemView` | `(call?: any) => JSX.Element` | Custom component for the entire call log item. | +| `TrailingView` | `(call?: any) => JSX.Element` | Custom component for the trailing view of each call log item. | +| `AppBarOptions` | `() => JSX.Element` | Custom options to render in the AppBar. | +| `callLogRequestBuilder` | `any` | Builder for custom call log requests. | +| `datePattern` | `ValueOf` | Date format pattern for call logs. | +| `showBackButton` | `boolean` | Flag to show the back button in the header. | +| `EmptyView` | `() => JSX.Element` | Custom component to render when the call log list is empty. | +| `ErrorView` | `(e: CometChat.CometChatException) => JSX.Element` | Custom component to render in case of an error. | +| `LoadingView` | `() => JSX.Element` | Custom component to render while loading call logs. | +| `hideError` | `boolean` | Flag to hide the error view. | +| `onCallIconPress` | `(item: any) => void` | Callback when the call icon is pressed. | +| `onError` | `(e: CometChat.CometChatException) => void` | Callback for handling errors. | +| `onBack` | `() => void` | Callback for when the back button is pressed. | +| `onItemPress` | `(call: any) => void` | Callback for when a call log item is pressed. | +| `style` | `DeepPartial` | Custom style overrides for the call logs. | +| `outgoingCallConfiguration` | `CometChatOutgoingCallInterface` | Configuration for outgoing calls. | +| `onLoad` | `(list: any[]) => void` | Callback when the list is fetched and loaded. | +| `onEmpty` | `() => void` | Callback when the list is empty (no items). | +| `onItemLongPress` | `(prop: { call: any }) => void` | Called on a long press of the default list item view. | +| `hideHeader` | `boolean` | Hide the toolbar header. | +| `hideLoadingState` | `boolean` | Hide the loading state. | +| `addOptions` | `(call: any) => MenuItemInterface[]` | Append more menu items on top of the default menu items for a call log. | +| `options` | `(call: any) => MenuItemInterface[]` | Replace the default menu items entirely for a call log. | + +#### Renamed Properties +| V4 Name | V5 Name | Type | Description | +|--------------------------|---------------------|-------------------------------|----------------------------------------------------------------------------------| +| `TailView` | `TrailingView` | `(param: { call?: any }) => JSX.Element` → `(call?: any) => JSX.Element` | Signature and name updated for trailing view. | +| `ListItemView` | `ItemView` | `(param: { call?: any }) => JSX.Element` → `(call?: any) => JSX.Element` | Signature and name updated for item view. | +| `EmptyStateView` | `EmptyView` | `() => JSX.Element` | Custom component for empty state. | +| `ErrorStateView` | `ErrorView` | `() => JSX.Element` → `(e: CometChat.CometChatException) => JSX.Element` | Signature and name updated for error view. | +| `LoadingStateView` | `LoadingView` | `() => JSX.Element` | Custom component for loading state. | +| `callLogsStyle` | `style` | `CallLogsStyleInterface` → `DeepPartial` | Style object renamed and type changed. | +| `options` | `options` | Function signature updated | Now receives `(call: any)` instead of `{ message: any }`. | +| `datePattern` | `datePattern` | Type updated | Now uses `ValueOf`. | + + +#### Removed Properties +| V4 Name | Type | Description | +|--------------------------|--------------------------|----------------------------------------------------------------------------------| +| `title` | `string` | Title of the call log list component. | +| `emptyStateText` | `string` | Text to be displayed when the state is empty. | +| `errorStateText` | `string` | Text to be displayed when error occurs. | +| `loadingIcon` | `ImageType` | Icon to be displayed when loading. | +| `avatarStyle` | `AvatarStyleInterface` | Style configuration for avatar. | +| `listItemStyle` | `ListItemStyleInterface` | Style configuration for individual list items. | +| `headViewContainerStyle` | `StyleProp` | Custom styling for headViewContainer. | +| `bodyViewContainerStyle` | `StyleProp` | Custom styling for bodyViewContainer. | +| `tailViewContainerStyle` | `StyleProp` | Custom styling for tailViewContainer. | +| `missedAudioCallIconUrl` | `string` | Custom missed audio call icon URL. | +| `missedVideoCallIconUrl` | `string` | Custom missed video call icon URL. | +| `incomingAudioCallIconUrl` | `string` | Custom incoming audio call icon URL. | +| `incomingVideoCallIconUrl` | `string` | Custom incoming video call icon URL. | +| `outgoingAudioCallIconUrl` | `string` | Custom outgoing audio call icon URL. | +| `outgoingVideoCallIconUrl` | `string` | Custom outgoing video call icon URL. | +| `BackButton` | `JSX.Element` | Custom back button element. | +| `onInfoIconPress` | `(prop: { call: any }) => void` | Callback for info icon press. | +| `infoIcon` | `ImageType` | Info icon image. | +| `theme` | `CometChatTheme` | Theme configuration for the call logs component. | +| `hideSeperator` | `boolean` | Toggle visibility of separator. | + +--- + +## Next Steps + + + + Set up the v5 UI Kit and send your first message + + + Customize colors, fonts, and styles with the new theme system + + + Style individual components using the simplified v5 approach + + + Explore all v5 prebuilt UI components + + \ No newline at end of file diff --git a/ui-kit/react-native/url-formatter-guide.mdx b/ui-kit/react-native/url-formatter-guide.mdx new file mode 100644 index 000000000..a0ae318d3 --- /dev/null +++ b/ui-kit/react-native/url-formatter-guide.mdx @@ -0,0 +1,191 @@ +--- +title: "URL Formatter" +description: "Detect and style plain URLs, emails, and phone numbers as clickable links in CometChat React Native UI Kit." +--- + + + +| Field | Value | +| --- | --- | +| Package | `@cometchat/chat-uikit-react-native` | +| Key class | `CometChatUrlsFormatter` (extends `CometChatTextFormatter`) | +| Required setup | `CometChatUIKit.init(UIKitSettings)` then `CometChatUIKit.login("UID")` | +| Purpose | Auto-detects URLs, emails, and phone numbers in text messages and converts them to clickable links | +| Sample app | [GitHub](https://github.com/cometchat/cometchat-uikit-react-native/tree/v5/sample) | +| Related | [Custom Text Formatter](/ui-kit/react-native/custom-text-formatter-guide) · [Mentions Formatter](/ui-kit/react-native/mentions-formatter-guide) · [All Guides](/ui-kit/react-native/guide-overview) | + + + +`CometChatUrlsFormatter` extends [CometChatTextFormatter](/ui-kit/react-native/custom-text-formatter-guide) to detect URLs, email addresses, and phone numbers in text messages and render them as clickable links using React Native's `Linking` API. + +--- + +## Features + +| Feature | Description | +| --- | --- | +| URL detection | Automatically detects HTTP/HTTPS URLs | +| Email detection | Detects email addresses and opens mail client | +| Phone detection | Detects phone numbers and opens dialer | +| Custom styling | Customize link text color and font | +| Native linking | Uses React Native `Linking` API for native behavior | + +--- + +## Usage + +The `CometChatUrlsFormatter` is included by default in the UI Kit. You can also create a custom instance with custom styling: + + + +```tsx +import React, { useState, useEffect, useMemo } from "react"; +import { View, SafeAreaView } from "react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatUrlsFormatter, +} from "@cometchat/chat-uikit-react-native"; + +function ChatScreen(): React.JSX.Element { + const [chatUser, setChatUser] = useState(); + + useEffect(() => { + CometChat.getUser("uid").then((user) => { + setChatUser(user); + }); + }, []); + + const urlFormatter = useMemo(() => { + const formatter = new CometChatUrlsFormatter(); + formatter.setStyle({ + linkTextColor: "#1a0dab", + linkTextFont: { + fontSize: 16, + fontWeight: "500", + }, + }); + return formatter; + }, []); + + return ( + + {chatUser && ( + + + + + + )} + + ); +} + +export default ChatScreen; +``` + + + +--- + +## Customization + +### Styling Links + +Use the `setStyle` method to customize link appearance: + +```tsx +import { CometChatUrlsFormatter } from "@cometchat/chat-uikit-react-native"; + +const urlFormatter = new CometChatUrlsFormatter(); + +urlFormatter.setStyle({ + linkTextColor: "#007AFF", // iOS blue + linkTextFont: { + fontSize: 16, + fontWeight: "600", + }, +}); +``` + +### Style Properties + +| Property | Type | Description | +| --- | --- | --- | +| `linkTextColor` | `ColorValue` | Color of the link text | +| `linkTextFont` | `TextStyle` | Font styling for link text (fontSize, fontWeight, etc.) | + +--- + +## How It Works + +The `CometChatUrlsFormatter` uses regex patterns to detect: + +1. **URLs**: HTTP and HTTPS links +2. **Emails**: Email addresses (opens `mailto:` link) +3. **Phone numbers**: Phone numbers (opens `tel:` link) + +When a link is tapped, it uses React Native's `Linking` API to open the appropriate handler: + +```tsx +// Internal implementation +const handlePress = async () => { + let finalUrl = url; + if (!url.match(/^(https?|mailto|tel):/i)) { + finalUrl = `http://${url}`; + } + + const canOpen = await Linking.canOpenURL(finalUrl); + if (canOpen) { + Linking.openURL(finalUrl); + } +}; +``` + +--- + +## Combining with Other Formatters + +You can use multiple formatters together. The order matters — formatters are applied in sequence: + +```tsx +import { + CometChatUrlsFormatter, + CometChatMentionsFormatter, +} from "@cometchat/chat-uikit-react-native"; + +const urlFormatter = new CometChatUrlsFormatter(); +const mentionsFormatter = new CometChatMentionsFormatter(); + +// Apply mentions first, then URLs +const textFormatters = [mentionsFormatter, urlFormatter]; + + +``` + +--- + +## Next Steps + + + + Build custom inline text patterns. + + + Add @mentions with styled tokens. + + + Browse all feature and formatter guides. + + + Full working sample application on GitHub. + + diff --git a/ui-kit/react-native/users.mdx b/ui-kit/react-native/users.mdx index a822321d9..c8eb8b0e7 100644 --- a/ui-kit/react-native/users.mdx +++ b/ui-kit/react-native/users.mdx @@ -1,740 +1,1111 @@ --- title: "Users" +description: "Searchable, scrollable list of all available users with avatar, name, and online/offline status." --- + +```json +{ + "component": "CometChatUsers", + "package": "@cometchat/chat-uikit-react-native", + "import": "import { CometChatUsers } from \"@cometchat/chat-uikit-react-native\";", + "description": "Searchable, scrollable list of all available users with avatar, name, and online/offline status.", + "primaryOutput": { + "prop": "onItemPress", + "type": "(user: CometChat.User) => void" + }, + "props": { + "data": { + "usersRequestBuilder": { + "type": "CometChat.UsersRequestBuilder", + "default": "SDK default (30 per page)", + "note": "Pass the builder, not the result of .build()" + }, + "searchRequestBuilder": { + "type": "CometChat.UsersRequestBuilder", + "default": "undefined" + }, + "searchKeyword": { + "type": "string", + "default": "\"\"" + } + }, + "callbacks": { + "onItemPress": "(user: CometChat.User) => void", + "onItemLongPress": "(user: CometChat.User) => void", + "onBack": "() => void", + "onSelection": "(list: CometChat.User[]) => void", + "onError": "(error: CometChat.CometChatException) => void", + "onEmpty": "() => void", + "onLoad": "(list: CometChat.User[]) => void", + "onSubmit": "(list: Array) => void" + }, + "visibility": { + "hideHeader": { "type": "boolean", "default": false }, + "showBackButton": { "type": "boolean", "default": false }, + "hideSearch": { "type": "boolean", "default": false }, + "hideError": { "type": "boolean", "default": false }, + "stickyHeaderVisibility": { "type": "boolean", "default": true }, + "hideSubmitButton": { "type": "boolean", "default": true }, + "hideLoadingState": { "type": "boolean", "default": false }, + "usersStatusVisibility": { "type": "boolean", "default": true }, + "title": { "type": "string", "default": "\"Users\"" } + }, + "selection": { + "selectionMode": { + "type": "SelectionMode", + "values": ["single", "multiple", "none"], + "default": "none" + } + }, + "viewSlots": { + "ItemView": "(user: CometChat.User) => JSX.Element", + "LeadingView": "(user: CometChat.User) => JSX.Element", + "TitleView": "(user: CometChat.User) => JSX.Element", + "SubtitleView": "(user: CometChat.User) => JSX.Element", + "TrailingView": "(user: CometChat.User) => JSX.Element", + "LoadingView": "() => JSX.Element", + "EmptyView": "() => JSX.Element", + "ErrorView": "() => JSX.Element", + "AppBarOptions": "() => JSX.Element" + }, + "menu": { + "options": "(user: CometChat.User) => MenuItemInterface[]", + "addOptions": "(user: CometChat.User) => MenuItemInterface[]" + }, + "search": { + "searchPlaceholderText": { "type": "string", "default": "\"Search\"" } + } + }, + "events": [ + { + "name": "ccUserBlocked", + "payload": "CometChat.User", + "description": "Triggered when logged-in user blocks another user" + }, + { + "name": "ccUserUnblocked", + "payload": "CometChat.User", + "description": "Triggered when logged-in user unblocks another user" + } + ], + "sdkListeners": [ + "onUserOnline", + "onUserOffline" + ], + "compositionExample": { + "description": "User list wired to message view", + "components": [ + "CometChatUsers", + "CometChatMessageHeader", + "CometChatMessageList", + "CometChatMessageComposer" + ], + "flow": "onItemPress emits CometChat.User -> pass to MessageHeader, MessageList, MessageComposer" + }, + "types": { + "SelectionMode": { + "single": "Select one user at a time", + "multiple": "Select multiple users", + "none": "No selection mode" + } + } +} +``` + + +## Where It Fits + +`CometChatUsers` is a contact list component. It renders all available users and emits the selected `CometChat.User` via `onItemPress`. Wire it to `CometChatMessageHeader`, `CometChatMessageList`, and `CometChatMessageComposer` to build a standard two-panel chat layout. + +```tsx lines +import { useState } from "react"; +import { View, Text, StyleSheet } from "react-native"; +import { GestureHandlerRootView } from "react-native-gesture-handler"; +import { SafeAreaProvider } from "react-native-safe-area-context"; +import { + CometChatUsers, + CometChatMessageHeader, + CometChatMessageList, + CometChatMessageComposer, + CometChatThemeProvider, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -## Overview +function ChatApp() { + const [selectedUser, setSelectedUser] = useState(); + + return ( + + + + + + setSelectedUser(user)} /> + + {selectedUser ? ( + + + + + + ) : ( + + Select a user + + )} + + + + + ); +} -The Users is a [Component](/ui-kit/react-native/components-overview#components), showcasing an accessible list of all available users. It provides an integral search functionality, allowing you to locate any specific user swiftly and easily. For each user listed, the widget displays the user's name by default, in conjunction with their avatar when available. Furthermore, it includes a status indicator, visually informing you whether a user is currently online or offline. +const styles = StyleSheet.create({ + container: { flex: 1, flexDirection: "row" }, + sidebar: { width: 350 }, + chatArea: { flex: 1 }, + placeholder: { flex: 1, justifyContent: "center", alignItems: "center" }, +}); +``` -*** +--- -## Usage +## Minimal Render -### Integration +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -To use Users in your component, use the following code snippet: +function UsersDemo() { + return ; +} -```tsx App.tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code -return ; +export default UsersDemo; ``` -### Actions - -[Actions](/ui-kit/react-native/components-overview#actions) dictate how a component functions. They are divided into two types: Predefined and User-defined. You can override either type, allowing you to tailor the behavior of the component to fit your specific needs. +--- -##### onItemPress +## Filtering Users -Function invoked when a user item is clicked, typically used to open a user profile or chat screen. +Pass a `CometChat.UsersRequestBuilder` to `usersRequestBuilder`. Pass the builder instance — not the result of `.build()`. - - -```tsx +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onPressHandler = (user: CometChat.User) => { - //code -}; - -return ; +function FilteredUsers() { + return ( + + ); +} ``` - +### Filter Recipes + +| Recipe | Code | +| --- | --- | +| Friends only | `new CometChat.UsersRequestBuilder().friendsOnly(true)` | +| Online users only | `new CometChat.UsersRequestBuilder().setStatus("online")` | +| Limit to 15 per page | `new CometChat.UsersRequestBuilder().setLimit(15)` | +| Search by keyword | `new CometChat.UsersRequestBuilder().setSearchKeyword("alice")` | +| Hide blocked users | `new CometChat.UsersRequestBuilder().hideBlockedUsers(true)` | +| Filter by roles | `new CometChat.UsersRequestBuilder().setRoles(["admin", "moderator"])` | +| Filter by tags | `new CometChat.UsersRequestBuilder().setTags(["vip"])` | +| Specific UIDs | `new CometChat.UsersRequestBuilder().setUIDs(["uid1", "uid2"])` | + +Default page size is 30. The component uses infinite scroll — the next page loads as the user scrolls to the bottom. + +A separate `searchRequestBuilder` can be passed to filter the search list independently from the main list. - +Refer to [UsersRequestBuilder](/sdk/react-native/retrieve-users) for the full builder API. -*** +--- + +## Actions and Events -##### onItemLongPress +### Callback Props -Function executed when a user item is long-pressed, allowing additional actions like delete or block. +#### onItemPress - - -```tsx +Fires when a user row is tapped. Primary navigation hook — set the active user and render the message view. + +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onLongPressHandler = (user: CometChat.User) => { - //code -}; +function UsersWithPress() { + const handleItemPress = (user: CometChat.User) => { + console.log("Selected:", user.getName()); + }; -return ; + return ; +} ``` - +#### onItemLongPress + +Fires when a user item is long-pressed, allowing additional actions like block or report. + +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; - +function UsersWithLongPress() { + const handleLongPress = (user: CometChat.User) => { + console.log("Long pressed:", user.getName()); + }; -*** + return ; +} +``` -##### onBack +#### onSelection -`onBack` is triggered when you press the back button in the app bar. It has a predefined behavior; when clicked, it navigates to the previous activity. However, you can override this action using the following code snippet. +Fires when users are selected/deselected in selection mode. Requires `selectionMode` to be set. - - -```tsx +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onBackHandler = () => { - //code -}; +function UsersWithSelection() { + const handleSelection = (list: CometChat.User[]) => { + console.log("Selected:", list.length); + }; -return ; + return ( + + ); +} ``` - +#### onEmpty - +Fires when the user list fetch returns zero results. -*** +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; + +function UsersWithEmptyHandler() { + return ( + console.log("No users available")} /> + ); +} +``` -##### onSelection +#### onError -Called when a item from the fetched list is selected, useful for multi-selection features. +Fires on internal errors (network failure, auth issue, SDK exception). - - -```tsx +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onSelectionHandler = (selection: Array) => { - //code -}; - -return ( - -); +function UsersWithErrorHandler() { + return ( + { + console.error("CometChatUsers error:", error); + }} + /> + ); +} ``` - +#### onLoad - +Fires when the list is successfully fetched and loaded. -*** +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -##### onError +function UsersWithLoadHandler() { + const handleLoad = (list: CometChat.User[]) => { + console.log("Users loaded:", list.length); + }; -This action doesn't change the behavior of the component but rather listens for any errors that occur in the Users component. + return ; +} +``` - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +### Global UI Events + +`CometChatUIEventHandler` emits events subscribable from anywhere in the application. Subscribe in a `useEffect` and unsubscribe on cleanup. + +| Event | Fires when | Payload | +| --- | --- | --- | +| `ccUserBlocked` | The logged-in user blocks another user | `CometChat.User` | +| `ccUserUnblocked` | The logged-in user unblocks another user | `CometChat.User` | + +```tsx lines +import { useEffect } from "react"; +import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; -const onErrorHandler = (error: CometChat.CometChatException) => { - console.log("Error"); -}; +function useUserEvents() { + useEffect(() => { + const listenerId = "USER_EVENTS_" + Date.now(); + + CometChatUIEventHandler.addUserListener(listenerId, { + ccUserBlocked: (user: CometChat.User) => { + console.log("Blocked:", user.getName()); + }, + ccUserUnblocked: (user: CometChat.User) => { + console.log("Unblocked:", user.getName()); + }, + }); -return ; + return () => { + CometChatUIEventHandler.removeUserListener(listenerId); + }; + }, []); +} ``` - +### SDK Events (Real-Time, Automatic) - +The component listens to these SDK events internally. No manual attachment needed unless additional side effects are required. -*** +| SDK Listener | Internal behavior | +| --- | --- | +| `onUserOnline` | Updates the user's status dot to online | +| `onUserOffline` | Updates the user's status dot to offline | -##### onEmpty +--- -Called when the list is empty, enabling custom handling such as showing a placeholder message. +## Custom View Slots - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; +Each slot replaces a section of the default UI. Slots that accept a user parameter receive the `CometChat.User` object for that row. -const onEmptyHandler = () => { - console.log("Empty"); -}; +| Slot | Signature | Replaces | +| --- | --- | --- | +| `ItemView` | `(user: CometChat.User) => JSX.Element` | Entire list item row | +| `LeadingView` | `(user: CometChat.User) => JSX.Element` | Avatar / left section | +| `TitleView` | `(user: CometChat.User) => JSX.Element` | Name / title text | +| `SubtitleView` | `(user: CometChat.User) => JSX.Element` | Subtitle text | +| `TrailingView` | `(user: CometChat.User) => JSX.Element` | Right section | +| `LoadingView` | `() => JSX.Element` | Loading spinner | +| `EmptyView` | `() => JSX.Element` | Empty state | +| `ErrorView` | `() => JSX.Element` | Error state | +| `AppBarOptions` | `() => JSX.Element` | Header bar options | -return ; -``` +### ItemView - +Replace the entire list item row. - + + + -*** +```tsx lines +import { + CometChatUsers, + CometChatAvatar, + useTheme, +} from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text } from "react-native"; + +function CustomItemViewUsers() { + const theme = useTheme(); + + const getItemView = (user: CometChat.User) => { + return ( + + + + {user.getName()} + + + ); + }; + + return ; +} +``` -##### onLoad +### LeadingView -Invoked when the list is successfully fetched and loaded, helping track component readiness. +Replace the avatar / left section. - - -```tsx +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { View, Text } from "react-native"; + +function LeadingViewUsers() { + const getLeadingView = (user: CometChat.User) => { + return ( + + + {user.getName().charAt(0)} + + + ); + }; -const onLoadHandler = (list: CometChat.User[]) => { - console.log("Loading"); -}; - -return ; + return ; +} ``` - +### SubtitleView - +Replace the subtitle text. -*** + + + + +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { Text } from "react-native"; + +function SubtitleViewUsers() { + const getSubtitleView = (user: CometChat.User) => { + return ( + + {user.getStatus() === "online" ? "Online" : "Offline"} + + ); + }; -##### onSubmit + return ; +} +``` -Callback when submit selection button is pressed. +### TrailingView - - -```tsx +Replace the right section. + +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; +import { TouchableOpacity, Text } from "react-native"; + +function TrailingViewUsers() { + const getTrailingView = (user: CometChat.User) => { + return ( + console.log("Follow:", user.getName())}> + Follow + + ); + }; + + return ; +} +``` -const onSubmitHandler = (list: Array) => { - console.log("Final List", list); -}; +### AppBarOptions -return ; +Custom view for the header bar options. + + + + + +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { TouchableOpacity, Text } from "react-native"; + +function AppBarOptionsUsers() { + return ( + ( + console.log("Settings pressed")}> + Settings + + )} + /> + ); +} ``` - +### options - +Custom context menu actions for each user item. -### Filters +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -**Filters** allow you to customize the data displayed in a list within a Component. You can filter the list based on your specific criteria, allowing for a more customized. Filters can be applied using RequestBuilders of Chat SDK. +function OptionsUsers() { + const getOptions = (user: CometChat.User) => [ + { + text: "Block", + onPress: () => console.log("Block:", user.getName()), + }, + { + text: "Report", + onPress: () => console.log("Report:", user.getName()), + }, + ]; + + return ; +} +``` -##### 1. UserRequestBuilder +--- -The [UserRequestBuilder](/sdk/react-native/retrieve-users) enables you to filter and customize the user list based on available parameters in UserRequestBuilder. This feature allows you to create more specific and targeted queries when fetching users. The following are the parameters available in [UserRequestBuilder](/sdk/react-native/retrieve-users) +## Common Patterns -| Methods | Type | Description | -| -------------------- | -------------- | -------------------------------------------------------------------------------------- | -| **setLimit** | number | sets the number users that can be fetched in a single request, suitable for pagination | -| **setSearchKeyword** | string | used for fetching users matching the passed string | -| **hideBlockedUsers** | bool | used for fetching all those users who are not blocked by the logged in user | -| **friendsOnly** | bool | used for fetching only those users in which logged in user is a member | -| **setRoles** | Array\ | used for fetching users containing the passed tags | -| **setTags** | Array\ | used for fetching users containing the passed tags | -| **withTags** | bool | used for fetching users containing tags | -| **setUserStatus** | string | used for fetching users by their status online or offline | -| **setUIDs** | Array\ | used for fetching users containing the passed users | +### Custom empty state with CTA -**Example** +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { View, Text, TouchableOpacity } from "react-native"; + +function EmptyStateUsers() { + return ( + ( + + No users found + console.log("Invite users")}> + Invite users + + + )} + /> + ); +} +``` -In the example below, we are applying a filter to the UserList based on Friends. +### Friends-only list - - -```tsx +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; import { CometChat } from "@cometchat/chat-sdk-react-native"; + +function FriendsOnlyUsers() { + return ( + + ); +} +``` + +### Multi-select with submit + +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; +import { CometChat } from "@cometchat/chat-sdk-react-native"; -function App(): React.JSX.Element { - const usersRequestBuilder = new CometChat.UsersRequestBuilder() - .setLimit(5) - .friendsOnly(true); +function MultiSelectUsers() { + const handleSubmit = (users: Array) => { + console.log("Selected users:", users.length); + }; - return ; + return ( + + ); } ``` - +### Hide all chrome — minimal list + +```tsx lines +import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; + +function MinimalUsers() { + return ( + + ); +} +``` - +--- -##### 2. SearchRequestBuilder +## Styling -The SearchRequestBuilder uses [UserRequestBuilder](/sdk/react-native/retrieve-users) enables you to filter and customize the search list based on available parameters in UserRequestBuilder. This feature allows you to keep uniformity between the displayed UserList and searched UserList. +The component uses the theme system from `CometChatThemeProvider`. Pass a `style` prop to customize the appearance. -**Example** + + + - - -```tsx -import { CometChat } from "@cometchat/chat-sdk-react-native"; +```tsx lines import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -function App(): React.JSX.Element { - const usersRequestBuilder = new CometChat.UsersRequestBuilder() - .setLimit(5) - .setSearchKeyword("Alice"); - - return ; +function StyledUsers() { + return ( + + ); } ``` - +### Style Properties - +| Property | Type | Description | +| --- | --- | --- | +| `containerStyle` | `ViewStyle` | Style for the root container | +| `headerStyle` | `ViewStyle` | Style for the header section | +| `titleStyle` | `TextStyle` | Style for the header title | +| `titleSeparatorStyle` | `ViewStyle` | Style for section header separators | +| `itemStyle` | `object` | Style for list items (includes `avatarStyle`, `titleStyle`, `subtitleStyle`) | +| `searchStyle` | `object` | Style for the search bar | -### Events +--- -[Events](/ui-kit/react-native/components-overview#events) are emitted by a `Component`. By using event you can extend existing functionality. Being global events, they can be applied in Multiple Locations and are capable of being Added or Removed. +## Props -To handle events supported by Users you have to add corresponding listeners by using `CometChatUIEventHandler.addUserListener` +All props are optional unless noted. -| Events | Description | -| --------------- | --------------------------------------------------------------------- | -| ccUserBlocked | This will get triggered when the logged in user blocks another user | -| ccUserUnblocked | This will get triggered when the logged in user unblocks another user | +### EmptyView - - -```tsx -import { CometChatUIEventHandler } from "@cometchat/chat-uikit-react-native"; +Custom component displayed when there are no users. -CometChatUIEventHandler.addUserListener("USER_LISTENER_ID", { - ccUserBlocked: ({ item }) => { - //code - }, -}); +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in empty state | -CometChatUIEventHandler.addUserListener("USER_LISTENER_ID", { - ccUserUnblocked: ({ item }) => { - //code - }, -}); -``` +--- - +### ErrorView - +Custom component displayed when an error occurs. -## Customization +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in error state | -To fit your app's design requirements, you can customize the appearance of the User component. We provide exposed methods that allow you to modify the experience and behavior according to your specific needs. +--- -### Style +### hideError -Using Style you can customize the look and feel of the component in your app, These parameters typically control elements such as the color, size, shape, and fonts used within the component. +Hides the error state view. -You can set the styling object to the `CometChatUsers` Component to customize the styling. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - - - +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code -return ( - -); -``` +### hideHeader - +Hides the entire header bar. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** +--- -### Functionality +### hideLoadingState -These are a set of small functional customizations that allow you to fine-tune the overall experience of the component. With these, you can toggle the visibility of UI elements. +Hides the loading state while fetching users. -Below is a list of customizations along with corresponding code snippets +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -| Property | Description | Code | -| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | -| **hideHeader** | Used to toggle visibility for the toolbar/header | `hideHeader?: boolean` | -| **showBackButton** | Used to toggle visibility for back button | `showBackButton?: boolean` | -| **hideSearch** | Used to toggle visibility for search box | `hideSearch?: boolean` | -| **hideError** | Used to hide error on fetching users | `hideError?: boolean` | -| **stickyHeaderVisibility** | Used to hide section headers | `stickyHeaderVisibility?: boolean` | -| **selectionMode** | This method determines the selection mode for users, enabling users to select either a single user or multiple users at once. | `selectionMode={SelectionMode.multiple}` | -| **hideSubmitButton** | Used to toggle the visibility of the submit button when selectionMode is enabled. | `hideBackButton={true}` | -| **searchPlaceholderText** | Used to set search placeholder text | `searchPlaceholderText?: string;` | -| **hideLoadingState** | Used to toggle visibility for Loading state | `hideLoadingState?: boolean` | -| **usersStatusVisibility** | Used to toggle visibility for User status | `usersStatusVisibility?: boolean` | -| **searchKeyword** | Keyword used to fetch initial user list. | `searchKeyword?: string` | -| **title** | Title for the header. | `title?: string` | +--- -*** +### hideSearch -### Advanced +Hides the search bar. -For advanced-level customization, you can set custom views to the component. This lets you tailor each aspect of the component to fit your exact needs and application aesthetics. You can create and define your views, layouts, and UI elements and then incorporate those into the component. +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | -*** +--- -#### LoadingView +### hideSubmitButton -This method allows developers to set a custom loading view that is displayed when data is being fetched or loaded within the component. Instead of using a default loading spinner, a custom animation, progress bar, or branded loading screen can be displayed. +Hides the submit button when selection mode is enabled. -Use cases: +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -* Showing a skeleton loader for users while data loads -* Displaying a custom progress indicator with branding -* Providing an animated loading experience for a more engaging UI +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code -const getLoadingView = (): JSX.Element => { - //your custom loading view - //return jsx; -}; -return ; -``` +### ItemView - +Custom renderer for the entire list item row. - +| | | +| --- | --- | +| Type | `(user: CometChat.User) => JSX.Element` | +| Default | Built-in list item | -*** +--- -#### EmptyView +### LeadingView -Configures a custom view to be displayed when there are no users. This improves the user experience by providing meaningful content instead of an empty screen. +Custom renderer for the avatar / left section. -Examples: +| | | +| --- | --- | +| Type | `(user: CometChat.User) => JSX.Element` | +| Default | Built-in avatar | -* Displaying a message like "No users yet. Start a new chat!" -* Showing an illustration or animation to make the UI visually appealing -* Providing a button to start a new user +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code -const getEmptyView = (): JSX.Element => { - //your custom Empty view - //return jsx; -}; -return ; -``` +### LoadingView - +Custom component displayed during the loading state. - +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | Built-in loading indicator | -*** +--- -#### ErrorView +### onBack -Defines a custom error state view that appears when an issue occurs while loading users or messages. This enhances the user experience by displaying friendly error messages instead of generic system errors. +Callback fired when the back button is pressed. -Common use cases: +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -* Showing "Something went wrong. Please try again." with a retry button -* Displaying a connection issue message if the user is offline -* Providing troubleshooting steps for the error +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code -const getErrorView = (): JSX.Element => { - //your custom error view - //return jsx; -}; -return ; -``` +### onEmpty - +Callback fired when the user list is empty. - +| | | +| --- | --- | +| Type | `() => void` | +| Default | `undefined` | -*** +--- -#### LeadingView +### onError -This method allows developers to set a custom leading view element that appears at the beginning of each user item. Typically, this space is used for profile pictures, avatars, or user badges. +Callback fired when the component encounters an error. -Use Cases: +| | | +| --- | --- | +| Type | `(error: CometChat.CometChatException) => void` | +| Default | `undefined` | -* Profile Pictures & Avatars – Display user profile images with online/offline indicators. -* Custom Icons or Badges – Show role-based badges (Admin, VIP, Verified) before the user name. -* Status Indicators – Add an active status ring or colored border based on availability. +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getLeadingView = (user: CometChat.User): JSX.Element => { - //your custom leading view - //return jsx; -}; -return ; -``` +### onItemLongPress - +Callback fired when a user row is long-pressed. - +| | | +| --- | --- | +| Type | `(user: CometChat.User) => void` | +| Default | `undefined` | -*** +--- -#### TitleView +### onItemPress -This method customizes the title view of each user item, which typically displays the user’s name. It allows for styling modifications, additional metadata, or inline action buttons. +Callback fired when a user row is tapped. -Use Cases: +| | | +| --- | --- | +| Type | `(user: CometChat.User) => void` | +| Default | `undefined` | -* Styled Usernames – Customize fonts, colors, or text sizes for the name display. -* Additional Metadata – Show extra details like username handles or job roles. -* Inline Actions – Add a follow button or verification checkmark next to the name. +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTitleView = (user: CometChat.User): JSX.Element => { - //your custom title view - //return jsx; -}; -return ; -``` +### onLoad - +Callback fired when users are loaded. - +| | | +| --- | --- | +| Type | `(list: CometChat.User[]) => void` | +| Default | `undefined` | -*** +--- -#### TrailingView +### onSelection -This method allows developers to customize the trailing (right-end) section of each user item, typically used for actions like buttons, icons, or extra information. +Callback fired when users are selected/deselected. Requires `selectionMode` to be set. -Use Cases: +| | | +| --- | --- | +| Type | `(list: CometChat.User[]) => void` | +| Default | `undefined` | -* Quick Actions – Add a follow/unfollow button. -* Notification Indicators – Show unread message counts or alert icons. -* Custom Info Display – Display last active time or mutual connections. +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getTrailingView = (user: CometChat.User): JSX.Element => { - //your custom Trailing view - //return jsx; -}; -return ; -``` +### onSubmit - +Callback fired when the submit button is pressed. Requires `selectionMode` to be set. - +| | | +| --- | --- | +| Type | `(list: Array) => void` | +| Default | `undefined` | -#### ItemView +--- -This method allows developers to assign a fully custom ListItem layout to the Users component, replacing the default design. It provides complete control over the appearance and structure of each user item in the list. +### searchKeyword -Use Cases: +Pre-fills the search and filters the user list. -* Customizing User Display – Modify how user information (name, avatar, status) is presented. -* Adding Action Buttons – Include follow, message, or call buttons directly in the item view. -* Highlighting User Roles – Display user badges such as Admin, Moderator, or VIP. +| | | +| --- | --- | +| Type | `string` | +| Default | `""` | - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getItemView = (user: CometChat.User): JSX.Element => { - //your custom Item view - //return jsx; -}; -return ; -``` +--- - +### searchRequestBuilder - +Request builder with search parameters to fetch users. -**Example** +| | | +| --- | --- | +| Type | `CometChat.UsersRequestBuilder` | +| Default | `undefined` | - - - +--- -*** +### selectionMode -#### SubtitleView +Enables single or multi-select mode on list items. -This method customizes the subtitle view of each user item, typically shown below the user's name. It can display additional details such as user status, last seen time, or a brief bio. +| | | +| --- | --- | +| Type | `"single" \| "multiple" \| "none"` | +| Default | `"none"` | -Use Cases: +--- -* Last Active Time – Show "Online Now", "Last seen 2 hours ago". -* User Status – Display status messages like "Offine", "Available". +### showBackButton - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -import { CometChat } from "@cometchat/chat-sdk-react-native"; -//code -const getSubtitleView = (user: CometChat.User): JSX.Element => { - //your custom Subtitle view - //return jsx; -}; -return ; -``` +Shows the back button in the header. - +| | | +| --- | --- | +| Type | `boolean` | +| Default | `false` | - +--- -**Example** +### stickyHeaderVisibility - - - +Shows/hides alphabetical section headers (A, B, C…). -*** +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -#### AppBarOptions +--- -This method customizes the overflow menu, typically appearing as a three-dot (⋮) icon, allowing additional options for each user in the list. +### SubtitleView -Use Cases: +Custom renderer for the subtitle text. -* User Management Actions – "Block User", "Report", "Add to Favorites". -* Friendship & Communication – "Send Message", "Follow/Unfollow". -* Profile Settings – "View Profile", "Edit Contact Info". +| | | +| --- | --- | +| Type | `(user: CometChat.User) => JSX.Element` | +| Default | `undefined` | - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code -return ( - { - return ( - { - //do something - }} - > - Custom App Bar Options - - ); - }} - /> -); -``` +--- - +### TitleView - +Custom renderer for the name / title text. -**Example** +| | | +| --- | --- | +| Type | `(user: CometChat.User) => JSX.Element` | +| Default | Built-in title | - - - +--- -#### options +### TrailingView -This method sets a predefined list of actions that users can perform when they long press a user in the list. These options typically include: +Custom renderer for the right section. -* Muting notifications for a specific user. +| | | +| --- | --- | +| Type | `(user: CometChat.User) => JSX.Element` | +| Default | Built-in trailing view | -By customizing these options, developers can provide a streamlined and contextually relevant user experience +--- - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code +### usersRequestBuilder -const setMyOptions = (_user: CometChat.User) => { - return [ - //options - ]; - }; +Controls which users load and in what order. +| | | +| --- | --- | +| Type | `CometChat.UsersRequestBuilder` | +| Default | SDK default (30 per page) | -return ( - -); -``` +Pass the builder instance, not the result of `.build()`. + +--- - +### usersStatusVisibility - +Shows/hides the online/offline status indicator. -#### addOptions +| | | +| --- | --- | +| Type | `boolean` | +| Default | `true` | -This method extends the existing set of actions available when users long press a user item. Unlike setOptions, which replaces the default options, addOptionsAdds allows developers to append additional actions without removing the default ones. Example use cases include: +--- -Use Cases: +### title -* Adding a "Report Spam" action. -* Introducing a "Save to Notes" option. -* Integrating third-party actions such as "Share to Cloud Storage". +Custom title for the header. -This method provides flexibility in modifying user interaction capabilities. +| | | +| --- | --- | +| Type | `string` | +| Default | `"Users"` | - - -```tsx -import { CometChatUsers } from "@cometchat/chat-uikit-react-native"; -//code +--- -const addOptions = (_user: CometChat.User) => { - return [ - //options - ]; - }; +### AppBarOptions +Custom component for the header bar options. -return ( - -); -``` +| | | +| --- | --- | +| Type | `() => JSX.Element` | +| Default | `undefined` | + +--- - +### addOptions + +Function to append additional menu items to the default context menu. + +| | | +| --- | --- | +| Type | `(user: CometChat.User) => MenuItemInterface[]` | +| Default | `undefined` | + +--- + +### options + +Function to replace the default context menu items entirely. + +| | | +| --- | --- | +| Type | `(user: CometChat.User) => MenuItemInterface[]` | +| Default | `undefined` | + +--- + +### searchPlaceholderText + +Placeholder text for the search input. + +| | | +| --- | --- | +| Type | `string` | +| Default | `"Search"` | + +--- - +## Next Steps + + + + Display and manage the list of recent chats + + + Display and manage group conversations + + + Display the full chat interface after selecting a user + + + Customize the appearance of UI Kit components + + \ No newline at end of file