NodeChat. Part 1.

Alexei Kozachenko
Nov 16, 2018 · 2 min read

It has been a while since I worked with Node.js, and for some time I wanted to work on a web project. I also did not have much experience with React, except for a few small projects for my web programming class, so I though it would be useful and interesting.

This project — NodeChat is a group chat application written in Node and SocketIO. It is a very simple web chat application, that does not have many features (so far).

The project was divided into 2 parts: Server —” nodeChatServer”, and the web application itself — “nodeChatReact”.

I started with installing node packages for both projects, so I could run it.
The interface was simple and the page looked like a regular messenger: Messages from other user would appear on the left side, messages that I sent — on the right.

Image for post
Image for post

After that, I wanted to see how the server side worked. I added a couple of log messages just to see how new users login to chat, what happens when they enter the room or close the chat page.

So from the log I discovered that usernames of joined users, who were previously logged in, were not set properly.

‘User: undefined has joined. Y5gTv6hgXA3UHSzZAAAA‘
‘User: undefined has disconnected. Y5gTv6hgXA3UHSzZAAAA ‘

I found a piece of code responsible for checking if the user was previously logged in:

if (previousUsername !== null) {
this.setState({ isLoggedIn: true });

Here, userJoin() is the method that broadcasts a message that a new user has joined the chat. I noticed that 1) it was called twice, and secondly, that it was apparently triggered before setState was completed.

I decided to move userJoin() to the completion handler, which would only be called after the set of the state would be set. I combined all the setState calls into 1 call:

this.setState({ username: this.state.usernameInput }, function () {

Now, when I reloaded the page the username was set properly:

Log messages from server:
User 'chrome' has connected: 1c0i9oQWL4Ew4BcDAAAB
User: chrome has disconnected.1c0i9oQWL4Ew4BcDAAAB

I created a PR and continued looking for other issues, which I will tell about in the next post.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store