AlexDemzz
AlexDemzz

Reputation: 243

SocketIO dont fire first client events

I am building a chat app. The issue is that, socket.io does not emitthe keypress event on the first client, when fired.

I built this with Ionic 3 & Angular 5

Here's the "bug"

My view.html

 <p *ngIf="typing == true">... is typing</p>
 <ion-item no-lines>
   <ion-input
       type="text"
       placeholder="Message"
       [(ngModel)]="message"
       (keypress)="userIsTyping()">
   </ion-input>
 </ion-item>

My view.ts

userIsTyping() {
  this.socket.emit('typing');
  this.socket.on("updateTyping", (data) => {
    console.log('typingInSocket = ' + data.isTyping);
    this.typing = data.isTyping;
  });
  console.log('typing = ' + this.typing);

My server.js

io.on('connection', (socket) => {
  socket.on('typing', () => {
    socket.broadcast.emit('updateTyping', {
      isTyping: true
    });
    setTimeout(() => {
      socket.broadcast.emit('updateTyping', {
        isTyping: false
      });
    }, 2000);
  });

Do you have any solution ? Thanks you guys !

Upvotes: 0

Views: 192

Answers (1)

Matt Fletcher
Matt Fletcher

Reputation: 9220

Okay, so the issue is how you're going about defining your socket listener. You're setting the event listener for this.socket.on("updateTyping") inside the block of code that only runs once you start typing. So every time you start typing, you create a new duplicate event listener. However, because it's only defined when you start typing, the "is typing..." won't show up until you've typed at least one character, at which point it'll start listening.

The answer is basically to move that socket listener outside of the userIsTyping() function.

this.socket.on("updateTyping", (data) => {
  console.log('typingInSocket = ' + data.isTyping);
  this.typing = data.isTyping;
});

userIsTyping() {
  this.socket.emit('typing');
}

Upvotes: 1

Related Questions