Skip to content
Advertisement

Socket io connected users key value array

I’m trying to make a list of connected users using key and value pairs. The key will be the connected user, when I received a message I want to emit this to the receiver and sender (to and from) Now I’m stuck on the part where I want to add the new connected user. How do I add the user to the user to the array?

Second issue is the foreach is not a function

let connectedUsers: { [key: string]: Socket }

io.on('connection', (socket: Socket) => {
  socket.on('USER_CONNECTED', (profile: Profile) => {
    connectedUsers !== undefined &&
      Object.keys(connectedUsers).includes(profile.userId) &&
      Object.assign(connectedUsers, { [profile.userId]: socket })
    console.log(connectedUsers)
  })

  socket.on('MESSAGE_SENT', (message: ChatMessage) => {
    connectedUsers.forEach(cli => {
      if (cli.key = message.to || cli.key = message.from) {
        cli.emit('MESSAGE_RECIEVED', message)
      }
    });
  })

Advertisement

Answer

connectedUsers is not an array but an object, so you can’t use forEach to iterate it. The good news is that you don’t need it!

When connectedUsers is populated you can refactor on message function like

  socket.on('MESSAGE_SENT', (message: ChatMessage) => {
    connectedUsers[message.to].emit('MESSAGE_RECIEVED', message);
    connectedUsers[message.from].emit('MESSAGE_RECIEVED', message);
  })

To add a user to the object connectedUsers simply

 socket.on('USER_CONNECTED', (profile: Profile) => {
    connectedUsers = Object.assign(connectedUsers, { [profile.userId]: socket })          
    console.log(connectedUsers)
  })
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement