Relative Content

Tag Archive for javascriptreactjssocket.io

Socket.IO: Is it possible to emit and listen for events in the same client

Like the title says, I wanna know if I can establish a socket.io connection in my frontend and then make the same instance emit messages. Then listen for those same messages within the frontend? I am working on a chat app and want to enable real-time messaging. So according to my component code below, when a user sends a message, the handleSubmit function is called. Inside the handleSubmit function I’m making an AJAX request to upload the text message to the database through the backend server. For receving messages, currently, I only have a useEffect() hook which will execute fetchChats(). But this component currently doesn’t support real-time updates. So my question is how can I setup socket.io in this component. I would want the io connection to emit a message with message data including “recipientEmail” (which is the email id of the user we’re texting to). And then also constantly keep listening for a message, once a message is received it will check whether recipientEmail in the message’s metadata is equal to client (here I’m now talking from the 2nd user’s perspective, where client is the second user.)