'Problem with emitting a list of rooms in Socket io

First of all, I'm very new to socket.io, so if someone would lend a helping hand it would mean a lot! :)

I am making a simple chat app were a user can create or join chat rooms. I am using React for front-end and socket.io for the server. Im also using Typescript for both parts.

I want to send an array from the server to the client in the following structure, which I have called ClientListType:

 [ { room: "nameOfRoom", clients: [ "simon", "millie" ] }, { room: "anotherRoom", clients: [ "simon", "millie" ] } ]

I have made this function, which console.logs according to the same structure as above. So the function rooms variable is correct.

export async function getRooms(io: Server) {
  const rooms: ClientListType[] = [];
  for (let [id, socket] of io.sockets.adapter.rooms) {
    if (!socket.has(id)) {
      let theClients: string[] = [];
      (await io.in(id).fetchSockets()).map((item) =>
        theClients.push(item.data.nickname)
      );
      let roomObject = { room: id, clients: theClients };
      rooms.push(roomObject);
    }
  }
  console.log(rooms);
  return rooms;
} 

But when I'm calling for the above function and trying to console.log its' value, it returns an empty array.

socket.on("join", async (room: string) => {
    const shouldBroadcastRooms: boolean = !(await getRooms(io)).some(
      (e) => e.room === room
    ); //If the new room is not in the getRooms list, then this becomes true and a new room will be created.

    socket.join(room);
    if (shouldBroadcastRooms) {
      io.emit("roomList", getRooms(io));
      console.log(await getRooms(io));
    }

Why is it empty? In the function I set it to return the rooms variable, so I can't see why the log would be empty?

Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source