[Vuejs]-Listen to messageAdded with Twilio in a Vue.js App

0👍

Twilio developer evangelist here.

channel.getMessages is an asynchronous method that returns a Promise but you are using it like a synchronous method in your code which is why

if (messages.length > 0) {
  // this never gets hit.
  console.log(messages)
  VueThis.messages = messages.items
}

doesn’t get hit. In this case messages is an unfulfilled Promise object and messages.length is undefined which apparently doesn’t throw when you compare with 0.

On the other hand, listening for the messageAdded event looks correct, so I don’t know what’s going on there. I’d start by fixing the asynchronous event and see if that helps. To do so, use .then and .catch instead of try and catch like this:

setupChatClient(channel) {
  const VueThis = this
  channel.getMessages()
    .then(messagePage => {
      console.log(messagePage.items);
      VueThis.messages = messagePage.items;
    })
    .catch(err => console.error(err));

  channel.on('messageAdded', message => {
    // This never gets hit
    console.log('in listner')
    var x = {}
    x.type = message.type
    x.author = message.author
    x.data = { text: message.body }
    VueThis.messages.push(x)
  });

  // ... rest of function
}

Let me know if that helps at all.

Leave a comment