Client Side Code:
useEffect(() => {
socketRef.current = io.connect("...", { transports : ['websocket'] })
socketRef.current.emit("online", id)
socketRef.current.on("message", ({ name, message }) => {
setChat([ ...chat, { name, message , system: false } ])
})
/* Removed code for online and offline events */
return () => {
socketRef.current.disconnect()
}
},[ chat ])
Server Side Code:
io.on('connection', socket => {
socket.on('message', ({ name, message , userID }) => {
io.emit('message', { name, message , userID })
})
socket.on('online', ( userID ) => {
onlineApprovers.push({ user: userID , id: socket.id })
console.log(userID + ' is online')
io.emit('online', userID)
})
socket.on('disconnect', () => {
console.log(onlineApprovers.find(a => a.id === socket.id).user + ' is offline')
io.emit('offline', onlineApprovers.find(a => a.id === socket.id).user)
})
})
Description of functionality: Upon user visiting the site, their user id is obtained, an 'online' event is emitted to the backend which logs that user is online. When user leaves the site, socket disconnects and logs the user as offline.
The issue arises on the frontend where it enters an infinite loop, continuously logging 'userID is online' followed by 'userID is offline' even without closing the window.
/ edit /
Removing the code related to online and offline events stopped the infinite loop, however it broke the frontend's ability to receive data from the backend.