I'm using socket.io-client in my frontend (React) and socket.io in my backend (Express) application. On my server I created an event that when triggered should send a message to all users in a room, it looks something like this.
socket.on('connection', () => {
// OTHER SOCKET EVENT LISTENERS (join, etc.)
socket.on('my_event', async (roomId) => {
// DO SOME DATABASE STUFF
const response = ...;
socket.in(roomId).emit('my_event_response', response);
}
});
On my client looks something like this.
// socket.ts
export const socket = io(process.env.REACT_APP_SERVER_URL || '', { withCredentials: true });
export const SocketContext = React.createContext({} as Socket);
// parent.ts
export const ParentNode: FC = () => {
const roomId = ...;
return (
<SocketContext.Provider value={socket}>
<ChildNode roomId={roomId} />
</SocketContext.Provider>
);
}
// child.ts
export const ChildNode: FC = ({ roomId }) => {
const socket = useContext(SocketContext);
useEffect(() => {
socket.on('my_event_response', () => {
console.log("USER TRIGGERED EVENT")
})
return () => {
socket.off('my_event_response')
}
}, [socket]);
const handleClick = useCallback(() => {
socket.emit('my_event', roomId)
}, [socket, roomId]);
return (
<div>
<button onClick={handleClick} />
</div>
);
}
When a user clicks a button to trigger an event, the server correct catches it and emits the response to all the users BUT the user that emitted the original event (my_event). I checked to make sure I'm not re-render my component and missing the event somehow. Is there a way to fix this so that the user who emitted the original event also gets the response?
Use io.in(...).emit(...) because socket.to(...).emit(...) emits to everyone in the room except the sender whereas io.in(...).emit(...) emits to everyone including the sender.