React.useEffect(() => {
socket
.on(conversationName, (message) => {
// push into list messages a new one
});
}, [conversationName]);
When user chose a conversation on the sidebar, a conversation name will be sent back from backend and stored in React state called conversationName. I used an useEffect to catch that change
Also a socket is listening on event name conversationName to get new messages.
My problem is the message that user sent will be duplicated n times when he switch back to a specific conversation n times
For example, there are 2 conversations called A and B. He clicks to A, chit chat some messages, clicks to B and then clicks back to A. Any message he sent from now on is duplicated 2 times.
Looking for some advice, many thanks guys !
You need to clean up the listener when the effect fires again:
React.useEffect(() => {
const listener = (message) => {
// push into list messages a new one
};
socket.on(conversationName, listener);
return () => socket.off(conversationName, listener);
}, [conversationName]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With