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

222
Visualizações
How to use React client to receive a message from a Socket.io server?

I'm using a server (Node.js and Socket.io) to send a message between clients (React). I can send a message from Client 1 to Client 2, but for the second client to be able to visualize the message on the screen it has to click a button. What I'm trying to achieve is to for the Client 2 to be able to visualize the message sent by the Client 1 automatically, without clicking on any button, directly when the Client 1 sends the message to the server and the server emits it. Something like having a listener that is working permanently looking for each time that the servers send a "socket.emit("send_message", message)". The problem is that on the React client, my function "socket.on("send_message",...)" inside a useEffect that only works when I click the button.

Any help or references would be awesome, thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I'm not sure if this the right approach but it worked for me.

Assuming the socket has been setup to connect to some url,

let [socket, setSocket] = useState(null)
useEffect(() => setSocket(io(socket_connect_url), [])

Then you could setup a hook to detect the event 'someEvent' like so,

  useEffect(() => {
    if(!socket) return;
    socket.on('someEvent', (recv) =>{
        try{
            // Process recv message here
            console.log(recv);
        }catch(err){
            console.log(err)
        }
    }, [socket])
  })
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