Socket.emit() and socket.on() not working when app is refreshed?
hey guys so im currently using socket.io for a real time chat app and my issue is that i have a useEffect which runs only on component mount okay and that fires
socket.connect()
and then socket.emit
s an event but for some reason when i refresh the app the component mounts right? and that should fire the emit event right? but it doesnt? its not received in the backend for some reason
ive added console.logs to ensure my useEffect
runs and it does but in the backend i dont get any logs from the event it should catch π¦
now it does work when i visit another component and get back to the component that has the socket event but for some reason it doesn't work on app refresh in the browser
id like some help ill paste the code below
im getting this console.log("A user connected:", socket.id);
on the terminal but not console.log(Received login event for userId: ${userId});
when i refresh π¦2 Replies
useEffect
is run twice in strict development mode. useEffect
should return a function that tears down whatever the setup builds.
In your case, something like: return () => { socket.disconnect() }
.
I wouldn't think that would cause the issue you're seeing though. I notice that socket.emit("login", data.id)
only has one parameter. Is that where you're authenticating? Should it have a user id & a password?
Or, is socket
a state variable that persists between mountings?I think Iβve fixed itβ¦ I needed to wrap my emit in a socket.on(connect) event ?