4. Implementing Send Message functionality

Let’s go back to our Client’s Chat.js Component and add the following functionality to our <button>:

Now let’s create this.sendMessage function:

in Constructor add the following:

Great. You are now sending the message to the server every time you click ‘Send Message’, and then your message input is cleared so you can write another message. All we have to do now is tell the server to emit the message to everyone who’s socket is connected to our server.

In app.js on the server side add the following code:

What we are doing here is that we are emiting the info we received from the client (author and message) and we are sending it to every one else. Now all that’s left to do is to catch that emit on the client side and add the message to our messages array.

Back in the Chat.js component on the client side add the folloing in the constructor:

I will now post how all the files should look like:

Chat.js

app.js

This function will catch the emit sent from the server and add the object that looks like this {author: ‘Antonio’, message: ‘hello world’} to our Messages [] array. We already implemented a messages.map functionality so now every time you add a message you should see it in your chat. This is what your chat should look like: