Operating a single chat works perfectly; however, upon entering and exiting a chat screen before re-entering it, double messaging occurs, and the listener remains active despite being placed in the return of useEffect. I attempted the solution provided in this discussion: React Pubnub Chat. Message duplication or absence of messages
I'm hoping for assistance in pinpointing the issue. Thank you 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 is triggered as many times as you enter and exit the chat due to the listener not 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()
}
}, [])