javascripttypescriptreact-nativepubnub

pubnub removeListener doesn't trigger on useEffect return


While opening a single chat works flawlessly, entering a chat, then leaving the chat screen and entering the chat again causes double messaging and the listener isn't being removed despite placing it on the return in useEffect I've even tried the solution in this thread: React Pubnub Chat. Message dublication or no message at all

Hopefully, you guys can help me identify the issue. thanks in advance!

 useEffect(() => {
   
    const listener = {
      message: (envelope: any) => {
        if (envelope) {
          const message = {
            channel: envelope.channel,
            message: {
              ...envelope.message,
            },
            uuid: envelope.publisher,
            timetoken: envelope.timetoken,
          }

          dispatch(setMessage(message))
// this log activates the same amount of times you entered and left the chat, because the listener isn't being removed
          console.log('Message listener activated!') 
        }

        //   setLastTimeToken(message.timetoken)
      },
    }

    pubnub.addListener(listener)
    pubnub.setUUID(employer._id)


    pubnub.fetchMessages(
      {
        channels: [ch],
        count: 100,
      },
      (status, response) => {
        if (response.channels[ch]) {
          dispatch(setMessages(response?.channels[ch]))
        } else {
          dispatch(setMessages([]))
        }
      },
    )
    pubnub.subscribe({ channels: [ch] })

    const usersInfo = channel.split('_')
    if (channel != employer._id && usersInfo[1] !== 'job') {
      const deeberId = usersInfo[0]
      getCandidateById(deeberId).then(res => {
        dispatch(setSelectedChatCandidate(res))
      })
    }
    renderDisplayName()

    return () => {
      pubnub.removeListener(listener) 

      pubnub.unsubscribeAll()
    }

  }, [])

Solution

  • Upgrading the PubNub JS SDK fixed an issue that caused multiple callback triggering. https://www.pubnub.com/docs/sdks/javascript/changelog#uv4342u