Reputation: 67
I want to made one connection on one emit function at a time in socket io with react and node js, but it is making new connection every time when emit is called from frontend. Is there any solution for this?
Reactjs code:
socket.emit('getMessages', 1000,this.state.userData._id,id);
Nodejs Code:
client.on('getMessages', (interval,sID,rID) => {
try {
//get messages from mongodb
} catch (err) {
console.log(err);
}
client.on('disconnect', () => {
console.log(`Socket ${client.id} disconnected.`);
});
});
I want to get message IDs but every time I am sending new IDs it makes a new connection and sending previous messages as well.
Upvotes: 0
Views: 573
Reputation: 56
If you want something to only happen once you could use client.once(....). If you want the server to not listen for the event anymore after it was emitted once you could add client.removeListener('getMessages') at the end of your listener.
Hope this is helpful. Not sure what behaviour your looking for exactly though.
Upvotes: 1