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

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

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