Danny Boris Ov
Danny Boris Ov

Reputation: 69

Getting different socket id on 2 socket.on(event)

I am build a socket based app with react and node/express. Once doing a io.on('connection') event, a user is being added to a users array with the addUser({id:socket.id, name, room}) function which is invoked in socket.on('join') event. When trying to send a massage im using a socket.on('sendMsg') and calling the getUser(socket.id) function but for some reason, it send a different id to the 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 fuck 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 = (id) =>{
    console.log(users)
    return users.find(user=> user.id === id)
}

I have absolutly no idea why this happening. anyone?

Upvotes: 0

Views: 733

Answers (1)

Danny Boris Ov
Danny Boris Ov

Reputation: 69

Solved. My socket instance on the CLIENT side was renewing itself everytime

Upvotes: 0

Related Questions