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

142
Visualizações
Not able to listen to a socket event in ReactJs component

If I am trying to call the socket.on outside the component, It is working but when I use it in useEffect() It is not working?

import ChatBubble from "../components/Chatbubblebot";
import io from 'socket.io-client'

let data = [];

function Messagelist({ sendMessage }) {
  data.push(sendMessage);

  useEffect(() => {
    const socket = io.connect("http://localhost:5000")

    socket.on("admin",(payload) => {
      console.log("payload",payload);
      data.push({who:"him",message:payload})
    })
    
  })
  let list = () => {
    console.log("sendMessage",sendMessage.length);
    if (data === undefined && sendMessage.length === 0) {
    } else {
      return data.map((e) => <ChatBubble who={e.who} message={e.message} />);
    }
  };
  return <ul>{list()}</ul>;
}

export default Messagelist;```
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try defining the socket variable outside component.

var socket;

And then in the component useEffect:

socket = io.connect("http://localhost:5000")

Also,

the let data = []; should not be defined like that.

It should be a state variable of the component like below:

const [data, setData] = useState([]);

And when you get new message from socket:

socket.on("admin",(payload) => {
      console.log("payload",payload);
      let _data= data;
      _data.push({who:"him",message:payload});
      setData(_data);
 })
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