> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-rn-guide-message-privately.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Threaded Messages

> Threaded Messages — CometChat documentation.

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/javascript/3.0/messaging-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:

1. Text Message
2. Media Message
3. Custom Message.

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.

**Example to Send a Text Message in a thread in a user conversation.**

<Tabs>
  <Tab title="User">
    ```javascript theme={null}
    let textMessage = new CometChat.TextMessage(UID, "Hello", CometChat.RECEIVER_TYPE.USER);
    textMessage.setParentMessageId(100);

    CometChat.sendMessage(textMessage).then(
      message => {
          console.log('Message sent successfully', message);
      }, err => {
          console.log('err', err);
      }
    ) 
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    let receiverId = "UID",
      receiverType: string = CometChat.RECEIVER_TYPE.USER,
      textMessage: CometChat.TextMessage = new CometChat.TextMessage(receiverId, "Hello", receiverType),
      messageId: number = 100;

    textMessage.setParentMessageId(messageId);

    CometChat.sendMessage(textMessage).then(
      (message: CometChat.TextMessage) => {
          console.log('Message sent successfully', message);
      }, (error: CometChat.CometChatException) => {
          console.log('Message sending failed', error);
      }
    );
    ```
  </Tab>
</Tabs>

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.

### Receiving Real-Time Messages

The procedure to receive real-time messages is exactly the same as mentioned in the [Receive Messages](/sdk/javascript/3.0/messaging-receive-message). 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.

<Tabs>
  <Tab title="Message Listener">
    ```javascript theme={null}
    var listenerID = "UNIQUE_LISTENER_ID";
    var activeThreadId = 100;

    CometChat.addMessageListener(
    listenerID,
    new CometChat.MessageListener({
      onTextMessageReceived: textMessage => {
          if(textMessage.getParentMessageId() == activeThreadId) {
              console.log("Text message received for active thread.", textMessage);
          }
      },
      onMediaMessageReceived: mediaMessage => {
          if(mediaMessage.getParentMessageId() == activeThreadId) {
              console.log("Media message received for active thread.", mediaMessage);
          }
      },
      onCustomMessageReceived: customMessage => {
          if(customMessage.getParentMessageId() == activeThreadId) {
              console.log("Custom message received for active thread.", customMessage);
          }
      }
    })
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    var listenerID: string = "UNIQUE_LISTENER_ID",
      activeThreadId: number = 100;

    CometChat.addMessageListener(
      listenerID,
      new CometChat.MessageListener({
          onTextMessageReceived: (textMessage: CometChat.TextMessage) => {
              if (textMessage.getParentMessageId() == activeThreadId) {
                  console.log("Text message received for active thread.", textMessage);
              }
          },
          onMediaMessageReceived: (mediaMessage: CometChat.MediaMessage) => {
              if (mediaMessage.getParentMessageId() == activeThreadId) {
                  console.log("Media message received for active thread.", mediaMessage);
              }
          },
          onCustomMessageReceived: (customMessage: CometChat.CustomMessage) => {
              if (customMessage.getParentMessageId() == activeThreadId) {
                  console.log("Custom message received for active thread.", customMessage);
              }
          }
      })
    );
    ```
  </Tab>
</Tabs>

### Fetch all the messages for any particular 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.

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.

<Tabs>
  <Tab title="Fetch all message for a thread">
    ```javascript theme={null}
    let limit = 30;
    let parentMessageId = 1;
    let messagesRequest = new CometChat.MessagesRequestBuilder()
                          .setLimit(limit)
                          .setParentMessageId(parentMessageId)
                          .build();
         
    messagesRequest.fetchPrevious().then(
      messages => {
          console.log("Messages for thread fetched successfully", messages);
      }, error => {
          console.log("Message fetching failed with error:", error);
      }
    );
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    let limit: number = 30,
      parentMessageId: number = 1,
      messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder()
          .setLimit(limit)
          .setParentMessageId(parentMessageId)
          .build();

    messagesRequest.fetchPrevious().then(
      (messages: CometChat.BaseMessage[]) => {
          console.log("Messages for thread fetched successfully", messages);
      }, (error: CometChat.CometChatException) => {
          console.log("Message fetching failed with error:", error);
      }
    );
    ```
  </Tab>
</Tabs>

## 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.

<Tabs>
  <Tab title="User">
    ```javascript theme={null}
    let UID = "UID";
    let limit = 30;
    let messagesRequest = new CometChat.MessagesRequestBuilder()
                          .setUID(UID)
                          .setLimit(limit)
                          .hideReplies(true)
                          .build();
         
    messagesRequest.fetchPrevious().then(
      messages => {
          console.log("Messages fetched successfully", messages);
      }, error => {
          console.log("Message fetching failed with error:", error);
      }
    );
    ```
  </Tab>

  <Tab title="Group">
    ```javascript theme={null}
    let GUID = "GUID";
    let limit = 30;
    let messagesRequest = new CometChat.MessagesRequestBuilder()
                          .setGUID(GUID)
                          .setLimit(limit)
                          .hideReplies(true)
                          .build();
         
    messagesRequest.fetchPrevious().then(
      messages => {
          console.log("Messages fetched successfully", messages);
      }, error => {
          console.log("Message fetching failed with error:", error);
      }
    );
    ```
  </Tab>

  <Tab title="Typescript (User)">
    ```typescript theme={null}
    let UID: string = "UID",
      limit: number = 30,
      messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder()
          .setUID(UID)
          .setLimit(limit)
          .hideReplies(true)
          .build();

    messagesRequest.fetchPrevious().then(
      (messages: CometChat.BaseMessage[]) => {
          console.log("Messages fetched successfully", messages);
      }, (error: CometChat.CometChatException) => {
          console.log("Message fetching failed with error:", error);
      }
    );
    ```
  </Tab>

  <Tab title="Typescript (Group)">
    ```typescript theme={null}
    let GUID: string = "GUID",
      limit: number = 30,
      messagesRequest: CometChat.MessagesRequest = new CometChat.MessagesRequestBuilder()
          .setGUID(GUID)
          .setLimit(limit)
          .hideReplies(true)
          .build();

    messagesRequest.fetchPrevious().then(
      (messages: CometChat.BaseMessage[]) => {
          console.log("Messages fetched successfully", messages);
      }, (error: CometChat.CometChatException) => {
          console.log("Message fetching failed with error:", error);
      }
    );
    ```
  </Tab>
</Tabs>

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.
