Implementing chat commands with acknowledgments
In addition to sending and receiving messages, chat apps often offer a way to send commands to the client and/or server. For example, we could send a /clear command to clear our local messages list. Or we could send a /rooms command to get a list of rooms that we are in. Follow these steps to implement chat commands:
- Edit
src/hooks/useChat.jsand adjust thesendMessagefunction inside it. First, let’s make it anasyncfunction:  async function sendMessage(message) { - Replace the contents of the function with the following. We first check whether the message starts with a slash (
/). If so, then we get the command by removing the slash and use aswitchstatement:Â Â Â Â if (message.startsWith('/')) { Â Â Â Â Â Â const command = message.substring(1) Â Â Â Â Â Â switch (command) { - For the
clearcommand, we simply set the array of messages...