Search code examples
javascriptreactjssocket.io

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;```

Solution

  • 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);
     })