Vikrant Pradhan
Vikrant Pradhan

Reputation: 167

socket.emit() does not work when used immediately after creating the socket object but works when i call it on click events?

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.

Upvotes: 0

Views: 590

Answers (1)

Tim VN
Tim VN

Reputation: 1193

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.

Upvotes: 1

Related Questions