Home > Software engineering >  How to pass Map Object as a function parameter
How to pass Map Object as a function parameter

Time:11-19

I am developing a web application that I am currently trying to get to display all online users. In the backend, I am using Socket.IO in JavaScript and store all connected users into a map object and pass it to the front end when someone connects. After someone connects, I am trying to iterate over it to dynamically created elements on the frontend.

In the server:

var users = new Map();

io.on('connection', function(socket) {

    socket.on('user_connected', function(username) {
        console.log(`${username} has connected`);
        users.set(socket.id, username);
        io.emit('updateUsers', users);
    });
});

In the client:

var username = cookies.get('USERNAME');
var socket = io('http://localhost:4000');

socket.on('connect', function() {
    socket.emit('user_connected', username);
});

socket.on('updateUsers', function(data) {
    for (const [key, value] of data) {
        showOnlineTutors(value);
    }
});

I got an error that data cannot be iterated over, so I printed the object to the console and I'm not sure why it isn't passing directly as the Map object from the server, or if that's just how passing a Map object works, I'm not sure how to iterate over it assuming it holds all the values properly.

This is the object

CodePudding user response:

The socket.io documentation says:

Map and Set must be manually serialized

https://socket.io/docs/v4/emitting-events/#basic-emit

Therefore, change your code to:

io.emit('updateUsers', [...users.entries()]);
  • Related