DEV Community

Omer Farooq for TalkJS

Posted on • Edited on

How to add chat into a VUE.JS app with TalkJS chat API

Adding a live chat feature to a web app is often complex. However, with recent developments in the web dev community and the inception of TalkJS, this formidable task has become a breeze. TalkJS is a turnkey solution for adding live chat to any web app. It provides an ever-customizable user interface, flexible notifications, and a powerful chat API out of the box. In this tutorial, we will look at how we can add a chat to an existing vue.js application in a matter of minutes.

Application Overview

VueJS Chat 1
A Great University runs our fictitious application. It allows their students to take live lectures, but it lacks the ability to chat with professors and amongst themselves in real-time. Currently, the web app consists of a landing page where the student’s log in with their university credentials (Name, Email and Password). Once they log in, they are taken to the live lecture. For simplicity’s sake, we have assumed that there’s only one live lecture, which in our case is just a YouTube video, and that all the students are already authenticated. The currentUser object we will use throughout the tutorial will contain data that we’ve received from the backend after the login and auth process. Our focus is on integrating a chat into an existing Vue app and not creating a whole app from scratch.

Adding TalkJS to our application

We begin by adding TalkJS to our application. This can be done in one of two ways.
If you use the Node Package Manager run the following command, it will save it as a dependency in the packages.json:

> npm install talkjs –save
Enter fullscreen mode Exit fullscreen mode

If you use Yarn Package Manager, run the following command:

> yarn add talkjs
Enter fullscreen mode Exit fullscreen mode

Now that you have TalkJS installed, you need to signup on their website and register your application. This is a very simple process, at the end of which you will receive your APPID. Keep hold of this, it’s very important, and we will use this later.

Creating the chatbox Vue Component

Every Vue component is housed in its own .vue file. In this case, here are the steps to be followed

  • We will create a component called MessageBox in MessageBox.vue.
  • Under the template, we create a div, as shown in the image below.
  • The div has a ref attribute set to “talkjs-container” we will use this to mount the actual chat box in this div later.
  • The tag is only used as a placeholder until the chatbox loads. We have added some styling, but that is left to the reader’s discretion.
<template>
  <div
    class="col-xs-4"
    id="talkjs-container"
    ref="talkjs-container"
    style="width: 90%; margin-top: 10px; height: 900px">
    <i>Loading chat...</i>
  </div>
</template>
Enter fullscreen mode Exit fullscreen mode
  • Below is a template that is added through a script tag. This will contain all the setup and logic for the TalkJS chatbox. Here the first thing we need to do is import TalkJS. To do that, add the following at the start of the script section:
import Talk from talkjs;
Enter fullscreen mode Exit fullscreen mode
  • Next, we export this component and name it MessageBox. This component will accept one prop of type object that contains the user’s information.
  • It has two variables that it needs to maintain, so we add conversation and chatbox to the data function.
<script>
import Talk from "talkjs";
export default {
  name: "MessageBox",
  data() {
    return {
      conversation: null,
      chatbox: null,
    };
  },
  props: {
    currentUser: {
      type: Object,
      required: true,
    },
  },
Enter fullscreen mode Exit fullscreen mode


javascript
Our chatbox will render once our MessageBox component has mounted, and as such, all chatbox logic will have to run inside the mounted lifecycle function that Vue provides. The mounted function will be defined just below our props object, and it will look something like this.

Creating the Users

The Talk object we imported from TalkJS is promise-based. Hence we call the ready function and then add our logic as a call back to the .then() function. Here we create our use through Talk.User() function. It accepts a JSONobject with the ID, Name, Email, photo URL of our user, and a role we set to default. For the sake of demonstration, we have also added another dummy user Sebastian in the other variable. In your application, you would add your own users using their data from your database.

mounted() {
    Talk.ready.then(() => {
      // creating our user
      var me = new Talk.User({
        id: this.currentUser.id,
        name: this.currentUser.name,
        email: this.currentUser.email,
        photoUrl: "https://randomuser.me/api/portraits/men/83.jpg",
        role: "default",
      });

      // creating other users
      var other = new Talk.User({
        id: "654321",
        name: "Sebastian",
        email: "Sebastian@example.com",
        photoUrl: "https://randomuser.me/api/portraits/men/69.jpg",
        welcomeMessage: "Hey, how can I help?",
        role: "default",
      });
Enter fullscreen mode Exit fullscreen mode

Establishing a TalkJS Session

There can’t be a chat if there’s no chat session, hence we establish a talk session and add it to our browser’s window’s instance.

 // establishing a new session if one doesn't already exists
      if (!window.talkSession) {
        window.talkSession = new Talk.Session({
          appId: "YOU_APP_ID",
          me: me,
        });
      }
Enter fullscreen mode Exit fullscreen mode

The APPID you found on your dashboard will be used here to establish a connection if one doesn’t already exist. This connection will let us join chats and start conversations. You also specify the user trying to establish the connection by passing the current user as a theme object.

Creating a New or Joining an Existing Conversation

Next, we join or start an existing conversation. Each conversation on TalkJS has a unique id. These ids can be stored in your database and used when joining group conversations or a conversation with someone. For our demonstration we will hard code it to 1001, all the students joining this lecture will be added to the conversation with the ID 1001.

// connecting to a new or already existing conversation
      this.conversation = window.talkSession.getOrCreateConversation("1001");
      this.conversation.setAttributes({ subject: "Computational Theory 101" });

      // adding participants
      this.conversation.setParticipant(me);
      this.conversation.setParticipant(other);
Enter fullscreen mode Exit fullscreen mode

The getOrCreateConversation() function will fetch the conversation if it already exists or create a new instance. Note that we are initializing the conversation variable we defined earlier, this is so we can access the conversation object later if necessary. Once the conversation has been initialized, we add its participants, and naturally, it is going to be the two users, me and others we created beforehand.

Creating an Inbox and Mounting it

Like a usual conversation, we will initializethe inbox variable we defined above using the createInbox function of our talkSession. We will pass our conversation as the focus of this inbox by setting selected to our conversation.

// creating the actual inbox/chatbox
      this.inbox = window.talkSession.createInbox({
        selected: this.conversation,
      });
Enter fullscreen mode Exit fullscreen mode

Last but not the least, we will mount our inbox to the div we added a ref to in the template section. But before this, we need to ensure that the ref we are going to point to has been initialized. Which is why we will use Vue’s $nextTick() function. It will ensure that the following code runs only after the required div, and ref are rendered and are ready to be addressed. In order to mount the inbox, we just call the mount function on the inbox object and pass this ref of our div, which we set to “talkjs-container”.

The Result

VueJS Chat 2
With this we’ve successfully added a chat box to our application. This group chat supports up to 20 users in the basic plan and up to 40 in the growth plan; however, more refinements will drastically increase these limits, such as the rolling enterprise plan. The chatbox would look something like this. This is the default design, and you can change it endlessly from the TalkJS dashboard.

The below gif demonstrates the functional design of the Chatbox.

VueJS Chat Gif

Top comments (0)