Implementing commands to join and switch rooms
Let’s now test out the new structure by implementing commands to join and switch rooms on the chat app, as follows:
- Edit
backend/src/socket.jsand define a new listener below thechat.messagelistener, which will call thejoinRoomservice function when we receive achat.joinevent from the client:Â Â Â Â socket.on('chat.join', (room) => joinRoom(io, socket, { room }))As we can see, having a
joinRoomservice function makes it really simple to reuse the code to join a new room here. It already sends a system message telling everyone that someone joined the room, just like it does when the user joins thepublicroom by default upon connection. - Edit
src/components/ChatMessage.jsxand displayroom:export function ChatMessage({ room, username, message, replayed }) { Â Â return ( Â Â Â Â <div style={{ opacity: replayed ? 0.5 : 1.0 }}> Â Â Â Â Â &...