Real time private chatting app using React, Nodejs, mongodb and Socket.io — Part 3

Connecting Angular application to Socket Server and Implementing Real-time chat list

Shashank Tiwari
8 min readOct 20, 2019

--

Originally published at https://www.codershood.info on October 20, 2019.

This is the third part of the Building Real time private chatting app using React. In this part, you will implement below-listed features in your application,

  1. You will connect your React application to Socket Server.
  2. You will implement the Realtime chat list for the application.
  3. You will write the Socket Server Event to Emit the updated Chat List.
  4. Highlight the select user from the list of users

Before Going any further a little recap,
In the previous part of the series, we completed the Login/Registration process in our application. After Login/Registration, the application will redirect the user to a home page of the application. Once you redirected to the homepage, the application will check the session of the user by making an HTTP request.

As soon as the application finishes the session checking, we will connect this React to the Nodejs socket server. Once the socket server is connected, just after that we will subscribe to real-time chat list update. So let’s get our hands dirty and start integrating real-time goodness into our application.

If you are familiar with Angular, then you will like to read how to create Real-time private chatting app using Angular.

Connecting React application to Socket Server

We won’t just connect the Socket server by using the below code, I know in most of the article you have seen, read, and wrote this code to connect the Socket Server.

Here we will add a little extra sugar by passing a parameter while connecting to the socket server.

=> Which we will do by using the code shown below,

Now you may ask Why we need this in the first place?

Well, the answer is simple. We need userId to identify which user is just connected to the socket Server. Also, we will update the socket id of the connected user in MongoDB.

=> The updated socketId will be used at the different stages of the application.

=>Since you have everything ready to go, all you have to do is call establishSocketConnection()(This method is defined inside the chatSocketServer.js file) from Home Component class.

Open the home.js file and replate the componentDidMount method by below code in Home component class,

home.js:

As I said earlier, we will update the socketId of the user in the MongoDB database, hence we can use it later in the application. If you check the socket connection string in the network tab, you should see something similar to the below shown image.

As of now, I am using the Chrome browser. Though it has nothing to do with what kind of browser you use. Anyways make sure you are passing userid while connecting socket server.

Passing user id in socket connection

Now you have provided a userId as a parameter in socket connection. Let’s complete abstract work on the server-side.

Open the socket.js file and add the below code to it,

socket.js:

Explanation:

  • The first thing to notice here we are reading the userId parameter by using socket.request._query['userId'] .
  • Second, we haveaddSocketId() method to update the data in MongoDB.
  • And at the end, we have called rest of the socket server Event by callingthis.socketEvents() method.

Implementing a Realtime chat List

I have divided this section into smaller sections since covering everything into a single section would be very nosogenic to read and understand. Creating a chat list involves below-listed points,

  1. Creating ChatList component.
  2. Writing Markup for a chat list
  3. WritingChatList component Class.
  4. Writing Socket server Event.
  5. Updating user’s online status in ChatList
  6. Selecting a User from the chat list of the user.

By the end of this article, you will have a full full-fledged working chat list for your application. So let’s dig our teeth into it and finish it.

Creating ChatList component

Why a new component for ChatList? Though we can write all the markup and Code inside the Home Component. But, It’s not a good practice and your Home Component class will be heavy and long to manage.

=> Therefore first things first, you have to create ChatList component nothing so special about it.

=>Let’s import the ChatListcomponent into HomeComponent. Open the home.js and add the below line, so that you can show chatlist in your application,

home.js:

Now you add the<ChatList> into your home.js file, and So at this point, your home.js file should look like this.

home.js:

Writing Markup for a chat list

Open the chat-list.js and add the below-shown render method. The below code is ridiculously easy to understand.

=> The next thing is chatListUsers property of ChatList Component class.

=> In chatListUsers property we will store the list of the users. This variable is nothing but an array, which updates itself on certain stipulated conditions.

ChatList.js:

Writing ChatList component Class

At this point, your ChatList component will render nothing. So to make it work we will add some code to the ChatList component class. Basically, in this class, do two important things.

=> First we will update the chat list and the second, we will pass the data of the selected user from the list of users to the Conversation component.

=>But first, let’s add the necessary state properties required in ChatList component class, open the ChatList.js and add the below properties,

ChatList.js:

Now let’s add the code to update the chat list, this code will basically manipulate the chatListUsers property. So open the ChatList.js and add the below code.

ChatList.js:

We know what the above code does, let’s understand how the above code works!

Explanation :

  1. UsinggetChatList()method we are updating the list of the user, which is defined into the ChatSocketService service.
  2. For example, If a new user logs in into the system or an existing user goes offline in both the cases we will update the list of online users.
  3. Here I am emitting the complete list of online/offline users from the nodejs socket server to the user who just logged into the system.
  4. And, for the rest of users, those who are already online will get the users information who went offline or just logged in. This makes sense, right? Because sending the complete list of online users to each and every user is not good.
  5. Now if you see the above code there iselse if()code block, for the below task.
  6. If the response from the socket event contains the singleUser property which means the new socket connection is established.
  7. If the response contains the userDisconnected property then it means the user went and offline remove the user from the chat list.
  8. And In the end, In the else condition we will update the list of users in the else block.

Writing Socket Server Events to Emit the updated Chat List

All the above only happen if you have a Socket server and which responds to the updated chat list. Anyways, let’s go ahead and talk something constructive.

=> Here you will write socket.io.on listener on the server-side when a client requests it.

=> Once React asks for a chat list to Socket server, the socket will query the details from the database.

=> After querying, based on the user it emits the result.

So this was the basic idea, let’s see the code to implement the same. Open the socket.js of your nodejs project and add the below code,

socket.js:

Explanation:

The above code seems easy to understand. But me being me, I am gonna explain it anyway.

  1. First thing first, we will check for the validation. If all goes well, the process ahead else emit a response with an error message.
  2. Second, inside the try-catch block, we will execute all the things. Why ? because you never know when your code will explode.
  3. Just kidding,try-catch is there to handle the unknown exceptions and unhandled promise rejections. And I feel like it’s a good practice to follow.
  4. Then inside the try-catch block, you will first fetch the information about the user by calling getUserInfo(). Later you all thegetChatList() which is defined inside the QueryHandler class.
  5. Why are you emitting two socket Events? As I explained in the above section, you don’t wanna send the entire chat list to the user instead send only information about the user who goes online/offline.

Let’s take a look at those methods defined in the QueryHandlerclass. Open the query-handler.js and add the below code,

In the below code, We are just executing a MongoDB query. Based on the socketId parameter, we are projecting the result from the database.

query-handler.js:

Now the last method left is to fetch the chat list from the database. Honestly Speaking you are just fetching all the user from the database and displaying it to the front end based on the online/offline status.

Open the query-handler.js and add the below code. In the below code, we will fetch all the records from the database.

query-handler.js:

In the above code, we are executing the MongoDB query. This query will fetch the list of users from the database by using the given condition. After executing the query, it will return the result trough Promise.

Once you implement all this you should be properly working chat list as shown in below image,

Realtime Chat list

Selecting a user from the chat list to chat

Till now you have successfully implemented the chat list feature in your application. Let’s go one more step ahead and add the feature to highlight the user selected for the chatting.

=> In this section we will just highlight the selected user from the chat list.

=> Open the C hatList.js and replace the code, Here we are using bootstrap classes, so you don’t need to write any CSS for that.

ChatList.js:

Explanation:

  1. As you can see the method this.state.selectedUserId will return true or false, and with the help of that, we will show currently selected user.
  2. By comparing the user selected userId with the user id.

=> In ChatListComponent class, we have selectedUserId state property as shown below.

This property will hold the value of the selected user id. To complete this feature, add the below methods in the C hatList.js.

ChatList.js:

Explanation:

  1. selectedUser() method will update the selectedUserIdstate property. Also, this method will emit the latest selected user id using the behavior subject.
  2. Also, this method will call a props method, i.e. updateSelectedUser which will give the currently selected user to its parent component.

Finishing Note

I believe this part of the series was short as compare to others. Let’s recall one more time, what we implemented here before wrapping this part. We implemented below-listed features in our application,

  1. We connected our React application to Socket Server.
  2. We implemented the Realtime chat list for the application.
  3. We wrote the Socket Server Event to Emit the updated Chat List.
  4. Highlighted the select user from the list of users

The complete source code is available on Github.

For now, that’s it. I’ll see you in the next and the last of the series where will implement real-time chat features.
Feel free to share your opinions in the below comments box. If you like this article do share it and leave a clap.

--

--