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.js
and adjust thesendMessage
function inside it. First, let’s make it anasync
function: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 aswitch
statement:if (message.startsWith('/')) { const command = message.substring(1) switch (command) {
- For the
clear
command, we simply set the array of messages...