Sometimes, a custom property on socket object is undefined inside disconnect event handler #4082
-
I have a custom event class MySocket {
constructor() {
io.on('connection', (socket) => {
socket.on('register', (payload) => this.register(payload, socket));
socket.on('disconnect', () => this.disconnect(socket));
});
}
register(payload, socket) {
socket.userId = payload.userId;
}
disconnect(socket) {
console.log(socket.userId); // this is sometimes undefined
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Are you sure that I think the Another approach would be to save data in a Map, with the socket ID as key and data (like the user ID) as value and removing the key on disconnect. This way, you’ll never be dependent on the socket.io library to handle custom properties. |
Beta Was this translation helpful? Give feedback.
Are you sure that
register
is triggered for that socket client before it disconnects?For debugging purposes, you could log the
socket.id
when the register function is called and check if thatsocket.id
has a user ID defined on disconnect.I think the
register
event is never triggered, and thus mo user ID is set for that client, before it disconnects.Another approach would be to save data in a Map, with the socket ID as key and data (like the user ID) as value and removing the key on disconnect. This way, you’ll never be dependent on the socket.io library to handle custom properties.