NodeChat. Part 1.

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.

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 });
  this.setState( { username: previousUsername }, ()=>{           this.userJoin();           
});
  this.userJoin();
  this.setState({ connected: true });            
this.setState({ previousUser: 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 () {
  // Hide the login page as the user has got a username now
this.setState({ isLoggedIn: true });
// Tell the server that we have got a new user
this.socket.emit('add user', this.state.username);
// Set the username that the user chose in localstorage
// This is so that when we reload the page, we can get the username they had previously
localStorage.setItem('NodeChatUsername', this.state.username);
   // Set the connected global
this.setState({ connected: true });
});

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.