Make a new prop in socket io object and get undefined

Home / Uncategorized / Make a new prop in socket io object and get undefined

Question:
I was trying to store data into a socket prop that I can reference it later. However, on others socket.on it comes out as undefined

Here is the code:var userlist = [‘Dang Huy’,’Alice’,’Bui Sam’, ‘Hai Hai’];
var onlineUser = [];

io.on(‘connection’, socket => {
socket.on(‘userOnline’, (data) => { //User Alice go in
if(userlist.includes(data)){
onlineUser.push(data);
io.sockets.emit(‘onlineUser’, onlineUser);
}
socket.user_name = data; // store data into user_name
console.log(socket.user_name + ‘ is online’); //logout Alice is online
})

socket.on(‘userSendMessage’, (data) => {
console.log(socket.user_name) // socket.user_name is undefined here!!
console.log(data) // still log out the message from the client side

io.sockets.emit(‘serverSendMessage’, ‘Hello’)
})

socket.on(‘disconnect’, function(){
onlineUser.splice(onlineUser.indexOf(socket.user_name), 1)
io.sockets.emit(‘onlineUser’, onlineUser)
})

})


Answer:
What do you mean by next event (could you provides an example?)Oh I notice something very wrong , you won’t never go to some event and that is purely normal, your socket scope variable is into {} & you ask it out of them, just move the listeners up:var userlist = [‘Dang Huy’,’Alice’,’Bui Sam’, ‘Hai Hai’];
var onlineUser = [];

io.on(‘connection’, socket => {
socket.on(‘userOnline’, (data) => { //User Alice go in
if(userlist.includes(data)){
onlineUser.push(data);
io.sockets.emit(‘onlineUser’, onlineUser);
}
socket.user_name = data; // store data into user_name
console.log(socket.user_name + ‘ is online’); //logout Alice is online
})
socket.on(‘userSendMessage’, (data) => {
console.log(socket.user_name) // socket.user_name is undefined here!!
console.log(data) // still log out the message from the client side

io.sockets.emit(‘serverSendMessage’, ‘Hello’)
})

socket.on(‘disconnect’, function(){
onlineUser.splice(onlineUser.indexOf(socket.user_name), 1)
io.sockets.emit(‘onlineUser’, onlineUser)
})
})
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *