Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

85
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda