0

I have an issue where when i call socket.emit() on the socket object after i instantiate the socket object it does not do anything. Like calling the socket emit function from the constructor when React app loads. But when i attach the same emit to a click event like clicking a button then it works correctly. Is this because of some some asynchronous process inside the socketio module?

for eg:

socket = io(<someurl>);
socket.emit('something') // this does not work

but calling the same thing inside a click event fires the emit.

1 Answers1

1

Yes. The socket is not connected yet, even if just for a few ms. Try sending that initial emit when connected:

const socket = io(); // with your parameters

socket.on('connect', () => {
    socket.emit('something');
});

Here's a list of events.

Tim VN
  • 1,183
  • 1
  • 7
  • 19