Currently, I am in the process of developing a socket-based application using React and Node/Express. As part of this project, there is an event listener set up for when a user connects with io.on('connection')
. Upon connection, the user is added to an array within the application using the
addUser({id:socket.id, name, room})
function, which is triggered during the socket.on('join')
event.
When attempting to send a message, I have implemented a handler for socket.on('sendMsg')
, but it seems that a different ID is being passed to the getUser(socket.id)
function.
io.on('connection',(socket)=>{
socket.on('join',({name,room})=>{
const user = addUser({id:socket.id, name, room})
socket.join(user.room)
socket.emit('message',{user:'admin',text:`${user.name}, welcome to the room ${user.room}`})
socket.broadcast.to(user.room).emit('message',{user:'admin', text:`${user.name} has joined`})
socket.on('disconnect',()=>{
console.log('usre left')
})
})
socket.on('sendMsg',(msg, callback)=>{
console.log('what the heck is this:', socket.id)
const user = getUser(socket.id)
console.log(user)
io.to(user.room).emit('message', {user: user.name, text: msg})
callback()
})
})
const addUser = ({id, name, room}) =>{
const existingUsers = users.find(user=>user.room === room && user.name === name)
if(existingUsers) {
console.log('not adding')
return {error:'User name is taken'}
}
const user = { id, name, room}
users.push(user)
console.log('users updated, ' ,users)
return user
}
const getUser = (userId) =>{
console.log(users)
return users.find(user=> user.id === userId)
}
I am at a loss as to why this unexpected behavior is occurring. Does anyone have any insights on this issue?