Closed bbarchuk closed 9 months ago
I was able to resolve the problem by just doing 3 new things:
io("http://localhost:8000")
After io("ws://localhost:8000")
..on()
method.The first point would be like this:
const socket: Socket = io("ws://localhost:8000")
In the second point i put that socket into a react ref (useRef hook), looking like this:
const sock = useRef<Socket>(socket)
And the last one and more important looks like this:
useEffect(() => {
const handleMessagesFromRoom = (message: string) => {
setMessages((prev) => [...prev, message]);
};
sock.current.on("message_from_room", handleMessagesFromRoom);
return () => {
sock.current.off("message_from_room", handleMessagesFromRoom);
};
}, []);
I hope this is helpful for anyone with the same type of error. Thanks
I'm encountering one issue where i can emit events from the client side (react) but not being capable of listen to events on the useEffect(). When i dispare an event everyone receives it in the network tab, so i don't know why i can't. It's worth to mention that im using rooms and when i change my server code to emit the event to everyone it triggers the useEffect, for example, intead of doing this:
socket.to(room).emit("foo", bar)
when i change to:io.emit("foo", bar)
it works fine, but clarily i don't want that 'cause i'm trying to use rooms.Socket.IO server version:
4.7.2
Server
Socket.IO client version Next js 14:
14.0.4
Client
With the above code i'm expecting to receive the message that anyone sent and update the messages state.