Home > front end >  After sending each message there becomes 2 more messages using socket io
After sending each message there becomes 2 more messages using socket io

Time:11-28

I have a React website.
I receive messages like this:

useEffect(() => {
    socket.on('message', message => {
        console.log(message)
    })
}, [socket])

I send messages like this:

socket.emit('chatMessage', { message, id })

Server side:

socket.on('chatMessage', ({ message }) => {
    socket.broadcast.emit('message', message)
})

First time there is 2 message (1 for the user who sent it), the next time there is 4, 6, 8 and so on.

CodePudding user response:

Short answer

useEffect(() => {
    socket.on('message', message => {
        console.log(message)
    })

     return () => {
       // cleanup code, disconnect
       // socket.disconnect()
     }
     
}, [socket])

Answer with explanation

If this does not solve the issue, I will delete this answer

CodePudding user response:

The problem with your code is you assume your component will never be recreated. But React does not provide such guarantees. And if you will ad logging at the place when you open asocket you will notice that for the first render it will be called 2 times. And because you do not have cleanup code the socket remains open for after component destruction. Thus duplicated messages.

Furthermore it would seem that your component is recreated on every message which multiplies the existing effect of duplication.

The solution in your case would be to close the connection in cleanup part of the effect.

  • Related