1

Recently I implemented Pusher ChatKit in my Vue project.

I have gone over the js documentation but I a confused over the flow of initiating the app so that I have active listeners for new messages.

I have 5 rooms that the currentUser is part of.

When I do

chatManager
    .connect()
    .then(currentUser => {
    })

I get the current user and I can access his rooms and roomSubscriptions.

1) What is the difference? Any room the user is part of should also be the one he is subscribed to, no?

The documentation says I need to subscribe to each of the user rooms in order to set up the onNewMessage() hook.

So I did it like this:

chatManager
    .connect()
    .then(currentUser => {
      this.initiateNewChatState(currentUser)
    })

initiateNewChatState(currentUser){
    for(let room of currentUser.rooms){
      currentUser.subscribeToRoom({
         roomId: room.id,
         hooks: {
         onNewMessage: message => {
          console.log(`Received new message ${message.text}`)
          this.$store.commit('CHATKIT_message', message)
         }
       },
       messageLimit: 10
     })
  }
}

2) But now when I receive a new message for only one room, the hook is triggered for every room hook (5 times).

Now once I have done the subscription loop I don't need to do this the next time I run chatManager.connect() cause the currentUser.roomSubscriptions is already filled with the rooms I subscribed the last time even before the this.initiateNewChatState() is invoked.

3) This begs the question, what is the correct flow for subscribing to user rooms that the user is already part of and how to detect new messages and new room creations (when someone starts to chat with is you)?

The documentation is really simplified and not implementable for a real-life case. Anybody has experience in this?

Thanks!

KasparTr
  • 2,328
  • 5
  • 26
  • 55

1 Answers1

0

Unfortunately, this is the only way right now. In Pusher ChatKit, every action depends on the current user & the user's subscription to rooms. A user is not necessarily subscribed to a room s/he is a member of. It has both pros and cons. But for now I can say, you can just set the messageLimit: 0 . This will not fetch all messages while you load the page for the first time. Rather fetch messages when a user clicks on a room to see the messages by using the following method:

           currentUser.subscribeToRoom({
                roomId: room.id,
                hooks: {
                    onNewMessage: (message) => {
                        // do something with the message
                    },
                    onUserStartedTyping : (user) => {
                        // do something with the user
                    },
                    onUserStoppedTyping : (user) => {
                        // do something with the user
                    },
                },
                messageLimit: 10
            });
Anurag
  • 482
  • 6
  • 23