Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

81
Views
SocketIO server not emitting event back to user who triggered event

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!