Receive message on Web

In previous tutorial, we made a component that connects to Amio Chat and can send messages. Let's add the ability to receive messages.

Update Component

  1. Add a method that processes a received message and adds it to the message list.
receiveMessage(message) {
  const messageText = message.content.payload
  this.messageList.push({
    direction: 'received',
    text: messageText
  })
}
  1. Register this method by calling amioChat.events.onMessageReceived(this.receiveMessage)

📘

Check out Amio Chat SDK documentation for details about the format of the received message.

And that's all you need to do to receive a message! As usual, the whole Chat.vue component is below.

<template>
    <div>
        <h2>Chat</h2>
        <div id="chat">
            <div>
                <p>Connected: {{connected}}</p>
            </div>
            <form @submit.prevent="sendMessage">
                <div>
                    <label for="message">Message:</label>
                    <input id="message" type="text" v-model="inputMessage">
                </div>
                <button type="submit">Send</button>
            </form>
            <div>
                <template v-for="(message, index) in messageList">
                    <p :key="index">{{message.direction}}: {{message.text}}</p>
                </template>
            </div>
        </div>
    </div>
</template>

<script>
  import {amioChat} from 'amio-chat-sdk-web'

  export default {
    data() {
      return {
        connected: false,
        messageList: [],
        inputMessage: ''
      }
    },
    methods: {
      sendMessage(e) {
        e.preventDefault()
        const messageText = this.inputMessage
        amioChat.messages.sendText(messageText)
          .then(() => {
            this.messageList.push({
              direction: 'sent',
              text: messageText
            })
          })

        this.inputMessage = ''
      },

      // 1. receive message and add it to list
      receiveMessage(message) {
        const messageText = message.content.payload
        this.messageList.push({
          direction: 'received',
          text: messageText
        })
      }
    },
    
    mounted() {
      // 2. register handler for a received message
      amioChat.events.onMessageReceived(this.receiveMessage)

      // TODO Find and paste the 'channel ID' from https://app.amio.io/administration/channels
      amioChat.connect({channelId: '{insert your channel ID here}'})
        .then(() => {
          this.connected = true
        })
    }

  }
</script>

<style scoped>
    #chat {
        text-align: left;
    }
</style>

Test it out

We will verify the messages are received in the next tutorial.