# Manage local conversations (/en/realtime-media/im/build/build-core-messaging/messages/manage-messages/react-native)

> For AI agents: see the complete documentation index at [llms.txt](/llms.txt).

In chat apps, a conversation is composed of all the messages in a peer-to-peer chat, chat group, or chatroom. The Chat SDK supports managing messages by conversations, including retrieving and managing unread messages, deleting the historical messages on the local device, and searching historical messages.

    This page introduces how to use the Chat SDK to implement these functionalities.

    ## Understand the tech [#understand-the-tech-4]

    SQLCipher is used to encrypt the database that stores local messages. The Chat SDK uses `ChatManager` and `ChatConversation` to manage local messages. The following are the core methods:

    * `ChatManager.getAllConversations`: Loads the conversation list on the local device.
    * `ChatManager.deleteConversation`: Deletes the specified conversation.
    * `ChatManager.deleteAllMessages`: Deletes all messages sent and received in a local conversation.
    * `ChatManager.deleteMessagesWithTimestamp`: Deletes messages sent and received in a certain period in a local conversation.
    * `ChatManager.pinConversation`: Pins a conversation.
    * `ChatManager.getPinnedConversationsFromServerWithCursor`: Retrieves the pinned conversations from the server with pagination.
    * `ChatManager.removeConversationFromServer`: Deletes the conversation and historical messages from the server.
    * `ChatManager.getMsgsWithMsgType`: Searches for messages from the local database.

    ## Prerequisites [#prerequisites-4]

    Before proceeding, ensure that you meet the following requirements:

    * You have integrated the Chat SDK, initialized the SDK and implemented the functionality of registering accounts and login. For details, see [Chat SDK quickstart](../../../../get-started-sdk).
    * You understand the API call frequency limits as described in [Limitations](../../limitations).

    ## Implementation [#implementation-4]

    This section shows how to implement managing messages.

    ### Retrieve conversations [#retrieve-conversations-4]

    Call `getAllConversations` to retrieve all the conversations on the local device:

    ```typescript
    ChatClient.getInstance()
      .chatManager.getAllConversations()
      .then(() => {
        console.log("Loading conversations succeeds");
      })
      .catch((reason) => {
        console.log("Loading conversations fails", reason);
      });
    ```

    ### Retrieve messages in the specified conversation [#retrieve-messages-in-the-specified-conversation-3]

    You can retrieve the messages in the specified conversation from the local database by specifying the conversation ID and chat type:

    ```typescript
    // Specify the conversation ID.
    const convId = "convId";
    // Whether to create a conversation if the specified one does not exist. If you set it as true, this method always returns a conversation object.
    const createIfNeed = true;
    // Set conversation type. For details, see descriptions in ChatConversationType.
    const convType = ChatConversationType.PeerChat;
    // Call getConversation to retrieve the specified conversation.
    ChatClient.getInstance()
      .chatManager.getConversation(convId, convType, createIfNeed)
      .then((conversation) => {
        console.log("Getting conversations succeeds", conversation);
      })
      .catch((reason) => {
        console.log("Getting conversations fails.", reason);
      });
    ```

    ### Retrieve the count of unread messages in the specified conversation [#retrieve-the-count-of-unread-messages-in-the-specified-conversation-3]

    Refer to the following code example to retrieve the count of unread messages:

    ```typescript
    // Specify the conversation ID.
    const convId = "convId";
    // Specify the conversation type. For details, see descriptions in ChatConversationType.
    const convType = ChatConversationType.PeerChat;
    // Call getConversationUnreadCount to retrieve the count of unread messages in the current conversation.
    ChatClient.getInstance()
      .chatManager.getConversationUnreadCount(convId, convType)
      .then((count) => {
        console.log("Getting conversations succeeds: ", count);
      })
      .catch((reason) => {
        console.log("Getting conversations fails.", reason);
      });
    ```

    ### Retrieve the count of unread messages in all conversations [#retrieve-the-count-of-unread-messages-in-all-conversations-3]

    Refer to the following code example to retrieve the count of all unread messages:

    ```typescript
    ChatClient.getInstance()
      .chatManager.getUnreadCount()
      .then((count) => {
        console.log("Getting all conversations succeeds: ", count);
      })
      .catch((reason) => {
        console.log("Getting all conversations fails.", reason);
      });
    ```

    ### Retrieve messages of a certain type in a local conversation [#retrieve-messages-of-a-certain-type-in-a-local-conversation]

    You can call the `getMsgsWithMsgType` method to retrieve messages of a certain type in a conversation in the local database. You can retrieve a maximum of 400 messages each time. If no message is retrieved, the SDK returns an empty list. To use this function, you need to upgrade the SDK to 1.3.0 or later.

    ```typescript
    // convId: The conversation ID.
    // convType: The conversation type, which is `PeerChat` for one-to-one chat, `GroupChat` for group chat, and `RoomChat` for chat room chat.
    // msgType: The message type.
    // direction: The message search direction
    // `ChatSearchDirection.UP`: Messages are retrieved in the descending order of the Unix timestamp included in them.
    // `ChatSearchDirection.DOWN`: Messages are retrieved in the ascending order of the Unix timestamp included in them.
    // timestamp: The starting Unix timestamp in the message for query. The unit is millisecond. After this parameter is set, the SDK retrieves messages, starting from the specified one, according to the message search direction.
    // If you set this parameter as a negative value, the SDK retrieves messages, starting from the current time, in the descending order of the timestamp included in them.
    // count: The maximum number of messages to retrieve each time. The value range is [1,400].
    // sender：The message sender, which is the user ID of the peer user for one-to-one chat or group ID for group chat.
    // isChatThread: Whether the conversation is a thread conversation.
    ChatClient.getInstance()
      .getMsgsWithMsgType({
        convId,
        convType,
        msgType,
        direction,
        timestamp,
        count,
        sender,
        isChatThread,
      })
      .then((messages) => {
        console.log("get message success");
      })
      .catch((reason) => {
        console.log("get message fail.", reason);
      });
    ```

    ### Mark unread messages as read [#mark-unread-messages-as-read-3]

    Refer to the following code example to mark the specified messages as read:

    ```typescript
    // Specify the conversation ID.
    const convId = "convId";
    // Specify the message ID that you want to mark as read.
    const msgId = "100";
    // Specify the conversation type. For details, see descriptions in ChatConversationType.
    const convType = ChatConversationType.PeerChat;
    // Call markMessageAsRead
    ChatClient.getInstance()
      .chatManager.markMessageAsRead(convId, convType, msgId)
      .then(() => {
        console.log("Marking message read succeeds: ");
      })
      .catch((reason) => {
        console.log("Marking message read fails.", reason);
      });
    ```

    You can also mark all unread messages of the specified conversation as read:

    ```typescript
    // Call markAllMessagesAsRead
    ChatClient.getInstance()
      .chatManager.markAllMessagesAsRead("convId", ChatConversationType.PeerChat)
      .then((count) => {
        console.log("Marking conversations read succeeds: ", count);
      })
      .catch((reason) => {
        console.log("Marking conversations read fails.", reason);
      });
    ```

    ### Clear chat history [#clear-chat-history-4]

    To clear the current user's chat history, including messages and conversations in individual chats, group chats, and chat rooms, you can call the `ChatManager#deleteAllMessageAndConversation` method. Additionally, you can choose whether to clear the chat history on the server. Note that clearing the chat history on the server means that you will not be able to retrieve conversations and messages from the server, although other users will not be affected.

    ```typescript
    ChatClient.getInstance()
      .chatManager.deleteAllMessageAndConversation(clearServerData)
      .then(() => {
        // Operation successful
      })
      .catch((error) => {
        // An error occurred
      });

    ```

    ### Delete conversations and historical messages [#delete-conversations-and-historical-messages]

    The SDK provides two methods, which enable you to delete the conversations and historical messages on the local device and on the server respectively.

    To delete them on the local device, call `deleteConversation`:

    ```typescript
    // Specify the conversation ID.
    const convId = "convId";
    // Whether to delete the messages as well.
    const withMessage = true;
    // Call deleteConversation
    ChatClient.getInstance()
      .chatManager.deleteConversation(convId, withMessage)
      .then(() => {
        console.log("Removing conversations succeeds: ");
      })
      .catch((reason) => {
        console.log("Removing conversations fails.", reason);
      });
    ```

    To delete them on the server, call `removeConversationFromServer`:

    ```typescript
    // Specify the conversation ID
    const convId = "convId";
    // Whether to delete the messages as well.
    const isDeleteMessage = true;
    // Specify the conversation type. For details, see descriptions in ChatConversationType.
    const convType = ChatConversationType.PeerChat;
    // Call removeConversationFromServer.
    ChatClient.getInstance()
      .chatManager.removeConversationFromServer(convId, convType, isDeleteMessage)
      .then(() => {
        console.log("Removing conversations succeeds: ");
      })
      .catch((reason) => {
        console.log("Removing conversations fails.", reason);
      });
    ```

    ### Delete all messages in a local conversation [#delete-all-messages-in-a-local-conversation-3]

    You can call `deleteAllMessages` to delete all messages sent and received in a local conversation:

    ```typescript
    // convId: The conversation ID.
    // convType: The conversation type, which is `Chat` for one-to-one chat, `Group` for group chat, and `Room` for room chat.
    ChatClient.getInstance()
      .chatManager.deleteAllMessages(convId, convType)
      .then(() => {
        console.log("delete message success");
      })
      .catch((reason) => {
        console.log("delete message fail.", reason);
      });
    ```

    ### Delete messages in a local conversation by time period [#delete-messages-in-a-local-conversation-by-time-period-3]

    You can call `deleteMessagesWithTimestamp` to delete messages sent and received in a certain period in a local conversation.

    ```typescript
    // startTs: The starting UNIX timestamp for message deletion.
    // endTs: The end UNIX timestamp for message deletion.
    ChatClient.getInstance()
      .chatManager.deleteMessagesWithTimestamp({ startTs, endTs })
      .then(() => {
        console.log("delete message success");
      })
      .catch((reason) => {
        console.log("delete message fail.", reason);
      });
    ```

    ### Search for messages using keywords [#search-for-messages-using-keywords-3]

    Search methods provided on this page can be used to search the local database for all types of messages except command messages, because command messages are not stored in the local database.

    Call `getMsgsWithMsgType` to search for messages by keywords, timestamp, and message sender:

    ```typescript
    // Specify the keyword,
    const keywords = 'key';
    // timestamp,
    const timestamp = 10000000;
    // the maximum count of searched messages,
    const maxCount = 10;
    // the message sender,
    const from = 'tom';
    // and the search direction. For details, see descriptions in ChatSearchDirection.
    const direction = ChatSearchDirection.UP;
    // Call getMsgsWithMsgType
    ChatClient.getInstance().chatManager.getMsgsWithMsgType(
                  keywords,
                  timestamp,
                  maxCount,
                  from,
                  direction
                )
      .then((messages[]) => {
        console.log("Searching conversations succeeds: ", messages);
      })
      .catch((reason) => {
        console.log("Searching conversations fails.", reason);
      });
    ```

    ### Search for messages in all conversations based on search scope [#search-for-messages-in-all-conversations-based-on-search-scope-3]

    You can call the `ChatManager#getMsgsWithKeyword` method to search in all conversations based on the search scope. This means that, in addition to setting the keywords, message timestamps, number of messages, sender, and search direction, you can also choose to search only in the message content, only in the message extension information, or in both.

    ```typescript
    ChatClient.getInstance()
      .chatManager.getMsgsWithKeyword({
        keywords, // Search keyword
        direction, // Search direction
        timestamp, // Message timestamp. Search starts from this timestamp in the specified direction.
        maxCount: 20, // Number of messages to request
        from: "", // Message sender
        searchScope: ChatMessageSearchScope.All, // Search scope. See the ChatMessageSearchScope type.
      })
      .then((res) => {
        // Operation succeeded. Handle the returned result.
      })
      .catch((error) => {
        // An error occurred.
      });
    ```

    ### Search for messages in the current conversation based on search scope [#search-for-messages-in-the-current-conversation-based-on-search-scope-3]

    You can search for messages in the current conversation based on the search scope. This means that, in addition to setting keywords, message timestamps, number of messages, sender, direction, and other parameters, you can also choose to search only in the message content, only in the message extension information, or in both. You can do this using one of the two methods:

    * Method 1

      ```typescript
      // Call directly
       ChatClient.getInstance()
         .chatManager.getConvMsgsWithKeyword({
           convId, // Conversation ID.
           convType, // Conversation type: `PeerChat` for single chat and `GroupChat` for group chat.
           keywords, // Search keywords
           direction, // Search direction
           timestamp, // The timestamp of the search message, starting from this timestamp and searching in the search direction `direction`.
           count: 20, // Requested number of messages
           sender: "", // Message sender
           isChatThread: false, // Whether it is a sub-area message. Sub-area messages are only used within sub-areas.
           searchScope: ChatMessageSearchScope.All, // Search scope, see `ChatMessageSearchScope` type for details.
         })
         .then((res) => {
           // todo: operation successful, process the returned result
         })
         .catch((error) => {
           // todo: an error occurred
         });
      ```

    * Method 2

      ```typescript
      // Called through the conversation object
           const conv = ChatClient.getInstance().chatManager.getConversation(
             convId,
             convType
           );
           conv
             .getMsgsWithKeyword({
               keywords, // Search keywords
               direction, // Search direction
               timestamp, // The timestamp of the search message, starting from this timestamp and searching in the search direction `direction`.
               count: 20, // Requested number of messages
               sender: "", // Message sender
               searchScope: ChatMessageSearchScope.All, // Search scope, see `ChatMessageSearchScope` type for details.
             })
             .then((res) => {
               // Operation successful, process the returned result
             })
             .catch((error) => {
               // An error occurred
             });
      ```

    ### Import messages [#import-messages-3]

    Call `importMessages` to import multiple messages to the specified conversation.

    ```typescript
    // Construct the messages.
    const msgs = [];
    ChatClient.getInstance()
      // Call importMessages.
      .chatManager.importMessages(msgs)
      .then(() => {
        console.log("Importing conversations succeeds: ");
      })
      .catch((reason) => {
        console.log("Importing conversations fails.", reason);
      });
    ```

    ## Next steps [#next-steps-4]

    After implementing managing messages, you can refer to the following documents to add more messaging functionalities to your app:

    * [Retrieve conversations and messages from the server](./retrieve-messages)
    * [Message receipts](./message-receipts)

    
  
      
  
      
  
