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.
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])
})