Skip to main content
Quick Reference for AI Agents & Developers
// Fetch conversations (recent chats)
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .build();
const conversations = await conversationsRequest.fetchNext();

// Get single conversation
const conversation = await CometChat.getConversation("user_uid", "user");

// Filter by type (user or group)
const request = new CometChat.ConversationsRequestBuilder()
  .setConversationType("user")  // or "group"
  .build();

// Unread conversations only
const request = new CometChat.ConversationsRequestBuilder()
  .setUnread(true)
  .build();

// Search conversations
const request = new CometChat.ConversationsRequestBuilder()
  .setSearchKeyword("John")
  .build();

// Tag a conversation
await CometChat.tagConversation("user_uid", "user", ["archived", "important"]);

// Convert message to conversation (for real-time updates)
const conversation = await CometChat.CometChatHelper
  .getConversationFromMessage(message);
Available via: SDK | REST API | UI Kits
Conversations represent chat threads between users or within groups. Use them to build your “Recent Chats” or “Inbox” view.

Fetch Conversations

Use ConversationsRequest to retrieve the logged-in user’s conversations:
const limit = 30;

const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(limit)
  .build();

conversationsRequest.fetchNext().then(
  (conversations) => {
    console.log("Conversations:", conversations);
  },
  (error) => {
    console.log("Error:", error);
  }
);
Maximum of 50 conversations can be fetched at once.

Pagination

Call fetchNext() repeatedly to load more conversations:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .build();

// Initial load
conversationsRequest.fetchNext().then((conversations) => {
  displayConversations(conversations);
});

// Load more (on scroll)
function loadMore() {
  conversationsRequest.fetchNext().then((conversations) => {
    appendConversations(conversations);
  });
}

Filter Options

By Conversation Type

Fetch only user or group conversations:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setConversationType("user")
  .build();

By Tags

Filter conversations by tags:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setTags(["archived", "important"])
  .build();

By User Tags

Filter user conversations by user tags:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setUserTags(["premium", "verified"])
  .build();

By Group Tags

Filter group conversations by group tags:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setGroupTags(["public", "official"])
  .build();

Unread Only

Requires Conversation & Advanced Search feature (Advanced & Custom plans). Enable in Dashboard → Chats → Settings → General Configuration.
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setUnread(true)
  .build();

Search Conversations

Requires Conversation & Advanced Search feature.
Search by user or group name:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setSearchKeyword("John")
  .build();

Include Blocked Users

By default, conversations with blocked users are hidden:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setIncludeBlockedUsers(true)
  .build();

With Blocked Info

Include block status in the response:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setWithBlockedInfo(true)
  .build();

Include Tags in Response

const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .withTags(true)
  .withUserAndGroupTags(true)
  .build();

AI Agent Conversations

Filter or exclude AI agent conversations:
const conversationsRequest = new CometChat.ConversationsRequestBuilder()
  .setLimit(30)
  .setHideAgentic(true)
  .build();
setHideAgentic() and setOnlyAgentic() are mutually exclusive. Use only one per request.

Get Single Conversation

Fetch a specific conversation:
const conversationWith = "user_uid";
const conversationType = "user";

CometChat.getConversation(conversationWith, conversationType).then(
  (conversation) => {
    console.log("Conversation:", conversation);
  },
  (error) => {
    console.log("Error:", error);
  }
);

Tag a Conversation

Add tags to organize conversations (e.g., archive, pin, categorize):
const conversationWith = "user_uid";
const conversationType = "user";
const tags = ["archived", "important"];

CometChat.tagConversation(conversationWith, conversationType, tags).then(
  (conversation) => {
    console.log("Tagged conversation:", conversation);
  },
  (error) => {
    console.log("Error:", error);
  }
);
Conversation tags are user-specific. If User A tags a conversation with User B, only User A sees that tag.

Convert Message to Conversation

When receiving real-time messages, convert them to conversation objects for your UI:
CometChat.CometChatHelper.getConversationFromMessage(message).then(
  (conversation) => {
    console.log("Conversation:", conversation);
    // Update your conversation list
  },
  (error) => {
    console.log("Error:", error);
  }
);
The converted conversation won’t include unreadMessageCount or tags. Manage unread counts client-side.

Conversation Object

PropertyMethodDescription
IDgetConversationId()Unique conversation identifier
TypegetConversationType()user or group
Last MessagegetLastMessage()Most recent message object
Conversation WithgetConversationWith()User or Group object
Unread CountgetUnreadMessageCount()Number of unread messages
TagsgetTags()Array of conversation tags
Updated AtgetUpdatedAt()Last activity timestamp

Example: Display Conversation List

conversations.forEach((conversation) => {
  const name = conversation.getConversationType() === "user"
    ? conversation.getConversationWith().getName()
    : conversation.getConversationWith().getName();
  
  const lastMessage = conversation.getLastMessage();
  const unreadCount = conversation.getUnreadMessageCount();
  
  console.log(`${name}: ${lastMessage?.getText()} (${unreadCount} unread)`);
});

All Filter Options

MethodDescription
setLimit(limit)Number of conversations (max 50)
setConversationType(type)user or group
setTags(tags)Filter by conversation tags
setUserTags(tags)Filter by user tags
setGroupTags(tags)Filter by group tags
withTags(true)Include tags in response
withUserAndGroupTags(true)Include user/group tags
setUnread(true)Only unread conversations
setSearchKeyword(keyword)Search by name
setIncludeBlockedUsers(true)Include blocked users
setWithBlockedInfo(true)Include block status
setHideAgentic(true)Exclude AI agent conversations
setOnlyAgentic(true)Only AI agent conversations

React Implementation Example

Here’s a complete React hook for managing conversations:
import { useEffect, useState, useCallback, useRef } from "react";
import { CometChat } from "@cometchat/chat-sdk-javascript";

export function useConversations() {
  const [conversations, setConversations] = useState([]);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const requestRef = useRef(null);

  // Initialize and load conversations
  useEffect(() => {
    requestRef.current = new CometChat.ConversationsRequestBuilder()
      .setLimit(30)
      .build();

    loadConversations();

    // Listen for new messages to update conversation list
    const listenerID = "CONVERSATION_LISTENER";
    CometChat.addMessageListener(
      listenerID,
      new CometChat.MessageListener({
        onTextMessageReceived: updateConversationFromMessage,
        onMediaMessageReceived: updateConversationFromMessage,
        onCustomMessageReceived: updateConversationFromMessage
      })
    );

    return () => {
      CometChat.removeMessageListener(listenerID);
    };
  }, []);

  const updateConversationFromMessage = async (message) => {
    try {
      const conversation = await CometChat.CometChatHelper
        .getConversationFromMessage(message);
      
      setConversations((prev) => {
        // Remove existing conversation if present
        const filtered = prev.filter(
          (c) => c.getConversationId() !== conversation.getConversationId()
        );
        // Add updated conversation at the top
        return [conversation, ...filtered];
      });
    } catch (error) {
      console.error("Failed to update conversation:", error);
    }
  };

  const loadConversations = useCallback(async () => {
    if (!requestRef.current || loading || !hasMore) return;

    setLoading(true);
    try {
      const fetched = await requestRef.current.fetchNext();
      setConversations((prev) => [...prev, ...fetched]);
      setHasMore(fetched.length === 30);
    } catch (error) {
      console.error("Failed to load conversations:", error);
    } finally {
      setLoading(false);
    }
  }, [loading, hasMore]);

  const markAsRead = useCallback(async (conversation) => {
    const conversationWith = conversation.getConversationType() === "user"
      ? conversation.getConversationWith().getUid()
      : conversation.getConversationWith().getGuid();

    await CometChat.markConversationAsRead(
      conversationWith,
      conversation.getConversationType()
    );

    // Update local state
    setConversations((prev) =>
      prev.map((c) => {
        if (c.getConversationId() === conversation.getConversationId()) {
          // Create updated conversation with 0 unread count
          // Note: In practice, you'd refetch or update the object
          return c;
        }
        return c;
      })
    );
  }, []);

  return {
    conversations,
    loading,
    hasMore,
    loadMore: loadConversations,
    markAsRead
  };
}

// Usage in component
function ConversationList({ onSelect }) {
  const { conversations, loading, hasMore, loadMore } = useConversations();

  return (
    <div>
      {conversations.map((conv) => {
        const partner = conv.getConversationWith();
        const lastMessage = conv.getLastMessage();
        const unread = conv.getUnreadMessageCount();

        return (
          <div key={conv.getConversationId()} onClick={() => onSelect(conv)}>
            <img src={partner.getAvatar()} alt={partner.getName()} />
            <div>
              <strong>{partner.getName()}</strong>
              <p>{lastMessage?.getText?.() || "No messages"}</p>
            </div>
            {unread > 0 && <span className="badge">{unread}</span>}
          </div>
        );
      })}
      {hasMore && (
        <button onClick={loadMore} disabled={loading}>
          {loading ? "Loading..." : "Load More"}
        </button>
      )}
    </div>
  );
}

Next Steps