socket.io-client icon indicating copy to clipboard operation
socket.io-client copied to clipboard

socket.io-client listening same event multiple times in reactjs

Open rajatlnweb opened this issue 5 years ago • 3 comments

Hello, I am creating a group chat application in reactjs, nodejs(expressjs) and socket.io. My code is all about 20-30 lines. When I clicked on send button, An event is emitted and I am listening that event on server side and emitting another event from server side and listening that event on client side in componentDidMount. But don't know why control is going inside socket event which is in componentDidMount multiple times, I mean it's listening to same event multiple times.

Please refer to below question for client side and server side code: https://stackoverflow.com/questions/56430669/same-event-emitting-multiple-times-in-socket-io-client-reactjs

Thanks.

rajatlnweb avatar Jun 05 '19 10:06 rajatlnweb

Hello! Unsubscribe should be done on unmount. Seems your component mounts multiple times, each time you add new listener.

Horat1us avatar Sep 19 '19 05:09 Horat1us

Can you please answer on reference stackoverflow question?

rajatlnweb avatar Sep 19 '19 05:09 rajatlnweb

@rajatlnweb Is there any update on this? The same things happen to me and I have written socket.on ("subscribe", () => {}); on useEffect and also tried with https://medium.com/@alexboots/using-react-context-with-socket-io-3b7205c86a6d as well as using it in constructor and componentDIdMount.

dhavalsoni2001 avatar Jan 03 '20 07:01 dhavalsoni2001

For future readers:

Please check our guide here: https://socket.io/how-to/use-with-react

Thanks!

darrachequesne avatar Jun 21 '23 00:06 darrachequesne