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

141
Views
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 answers
Answer question

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 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!