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.js
and define a new listener below thechat.message
listener, which will call thejoinRoom
service function when we receive achat.join
event from the client:socket.on('chat.join', (room) => joinRoom(io, socket, { room }))
As we can see, having a
joinRoom
service 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 thepublic
room by default upon connection. - Edit
src/components/ChatMessage.jsx
and displayroom
:export function ChatMessage({ room, username, message, replayed }) { return ( <div style={{ opacity: replayed ? 0.5 : 1.0 }}> &...