I am using socket.io (v4.0.1) to build a chat app with react and node. I would like to get a list of sockets (users) who have already joined a room so that when a users joins a room I can send a notification to them to let them know if there are other people online already. There are a lot of examples how to do this with earlier versions of socket.io but none seem to work with version 4. Here is my server code for this event:
// join a room (chat) with the chat id
socket.on('join chat', ({ chat, userId }) => {
socket.join(chat.id);
// this line is not working
const clients = Object.keys(io.sockets.adapter.rooms[chat.id].sockets);
// does not work
// var roster = io.sockets.clients('chatroom1');
const { users } = chat;
if (!chat.users) return console.log('users not defined');
// for each user in the conversation, send a notification to their own room
// telling them someone joined the chat
// want to let the user who joined (userId) know who is already there
chat.users.forEach(user => {
if (user._id === userId) return;
socket.in(user._id).emit('user joined', userId);
});
console.log(`User with id ${userId} joined chat with id ${chat.id}`);
});