Receiving duplicate messages with onTextMessageReceived

I am getting messages duplicated everytime i receive it.

async receiveMessages() {
    let { uid, myUserID } = this.state;

    var listenerID = "CHAT_SCREEN_LISTENER_ID";
   
    CometChat.addMessageListener(
      listenerID,
      new CometChat.MessageListener({
        onTextMessageReceived: (textMessage) => {
      
          console.log("console 0");

          if (
            textMessage.sender.uid == uid &&
            textMessage.receiverType == "user"
          ) {
         
            if (textMessage.sender.uid != myUserID) {
           

              CometChat.markAsRead(
                textMessage.id,
                textMessage.sender.uid,
                "user"
              );
              this.setState(
                (state) => {
                  return state.messages.push(textMessage);
                },
                () => {
                  console.log("console 3");
                }
              );
            }
 ......
      

     componentWillUnmount() {
        console.log("chatroomWillmount");
        CometChat.removeMessageListener(this.state.listenerId);
        this.props.fetchUnreadNotifications();
      }

Can you please guide me how to remove the messageListener everytime when i receive a new message?

@cometchat-pro/react-native-chat": “version”: “2.0.7”,

Hi @vishal, I’m Paarth from CometChat Customer Support Team.
Our Engineer will have a look at this and respond shortly.
Until then, feel free to contact me for any other assistance. Thank you.

Hello @vishal,

You can remove a Message Listener by using,

CometChat.removeMessageListener(listenerID);

where the listenerID is the id you set while adding the Message Listener.

Ok fixed it. It was only happening in the simulator, not in real device. But i am getting warnings like this:

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
in CometChatRoom (created by Connect(CometChatRoom))

Can you guide me how to remove all the listeners in the chat window page when unmounted?

Hello @vishal,

It looks like you are using setState() in componentWillUnmount(). Please make sure you do not try to setState() after the component is unmounted.

1 Like

Hi @vishal,
Just wanted to check with you if we have been able to solve both your issues.
Please let me know if there are any further issues that are preventing you from seamless usage of CometChat.
Looking forward to your response.
Regards,
Paarth Sabharwal

1 Like

Hello @vishal,

Closing due to inactivity.

Warm Regards,

CometChat Pro
Mayur Bhandari