Hacktoberfest – Added user is typing… feature using React and SocketIO

This blog post covers my 5th pull request of Hacktoberfest 2018!!!! For a few days I wasn’t sure if I would be able to reach the 5 PR goal.  I got super busy with another project, which I may put a blog post up about that project sometime. I was able to work hard on Hacktoberfest the past couple day’s and now I am done all 5 PR’s!!!

Back to the topic of this post I’ll put a summary blog post of Hacktoberfest soon.

I add the feature that show’s when a user is typing which was requested in issue #1 of the node chat project.  Here is the link to the pull request.

In order to accomplish this task I used two events on the server side. ‘typing’ and ‘stop typing’.

Server Code
socket.on('typing', function(){
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  socket.on('stop typing', function(){
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

For the client code I put the two event listener’s inside the componentDidMount().

The event listener for ‘typing’ add’s the user name to a state variable ‘userIsTyping’ which is an array of the user names that are typing.

The event listener for ‘stop typing’ removes the user name from ‘userIsTyping’.

Client Code
componentDidMount() {
  this.state.socket.on('typing', (user) => {
      if(this.state.username!==user.username){
        if(!this.state.userIsTyping.find(function(users){
              return users==user.username;
           })) {
          this.setState({userIsTyping: [...this.state.userIsTyping, user.username] });
        }
      } 
  });

  this.state.socket.on('stop typing', (user) => {
    if(this.state.username!==user.username){
       this.setState({userIsTyping: this.state.userIsTyping.filter(function(users) {
           returnusers!==user.username;
         })});
       }});
    }
  }
}

The function below is used to retrieve the content of the input field. It will emit ‘typing’ if there is anything inside the input field and it will emit ‘stop typing’ when there is nothing inside the input field.

setChatInput(event) {
  if(event.target.value !== ""){
    this.state.socket.emit('typing', this.state.username);
  } else if(event.target.value === ""){
    this.state.socket.emit('stop typing', this.state.username);
  }
  this.setState({ chatInput:event.target.value });
}

The end result looks like this:

Leave a Reply

Your email address will not be published. Required fields are marked *