Svelte

Even if you have a lot of Svelte experience, integrating with a new SDK can be a fiddly process. The easiest way to learn is by trying the features for yourself. But for that, you need a working project that you can play around with.

This quick-start guide will help you add TalkJS in your Svelte app for the first time. We cover the core concepts of TalkJS, and introduce you to its JavaScript SDK.

Prerequisites

To make the most of this tutorial, you will need:

  1. A TalkJS account
  2. A basic understanding of Svelte
  3. A Svelte app that you will add TalkJS to

Installing TalkJS

To get started, you will need to install TalkJS in your Svelte app:

npm install talkjs --save

Then, import TalkJS into the component you want to use for chat:

JavaScript
<script>
import Talk from 'talkjs';
</script>

TalkJS is loaded asynchronously to improve the performance of your site. Before we can use it, we need to make sure that TalkJS is fully loaded and ready to use. To do that, we wait for the Talk.ready promise to resolve before making any calls to the TalkJS SDK.

import { onMount } from 'svelte';
onMount(async () => {
await Talk.ready;
// Safe to use the SDK here
});

Talk.ready is a standard JavaScript promise, so you can call .then or await it at any point.

Creating users

In TalkJS, a 'User' is a person that uses your app. Typically, you will have one TalkJS user for each user in your own database. Each connection to TalkJS has to specify a 'Current User' to send messages as.

Usually, you would create users based on the data from your database. For this simple example, we'll hard-code one instead:

JavaScript
// After `await Talk.ready`
const currentUser = new Talk.User({
id: '1',
name: 'Henry Mill',
photoUrl: 'henry.jpeg',
welcomeMessage: 'Hello!',
role: 'default',
});

Remember, anything using the Talk API should only run after we await Talk.ready. There's not much point in a chat app with only one person using it, so let's create another user:

JavaScript
// After `await Talk.ready`
const otherUser = new Talk.User({
id: '2',
name: 'Jessica Wells',
photoUrl: 'jessica.jpeg',
welcomeMessage: 'Hello!',
role: 'default',
});

Connecting to TalkJS

To synchronize data between a browser tab and TalkJS, you need to create a new connection, known as a session. The session will stay open until the user navigates away from the page, and it automatically synchronizes data in both directions with the TalkJS servers.

To create a new session, you will need your 'App ID' and a user to send messages as (the 'Current User'). You can find YOUR_APP_ID in the TalkJS dashboard.

onMount(async () => {
await Talk.ready;
// Create users here
const session = new Talk.Session({
appId: 'YOUR_APP_ID',
me: currentUser,
});
});

Starting a conversation

So far, we have loaded TalkJS, created some users, and opened a connection to the server. Now we need to let them talk to each other.

A 'Conversation' is a place for two or more users to chat. That could mean a simple direct message between users, or it might be something fancier. TalkJS works with all kinds of conversations, from group chats to product-specific haggling.

We will use that last example, and create a conversation between 'Henry' and 'Jessica':

JavaScript
// After `Talk.ready` and creating users
const conversationID = Talk.oneOnOneId(currentUser, otherUser);
const conversation = session.getOrCreateConversation(conversationId);
conversation.setParticipant(currentUser);
conversation.setParticipant(otherUser);

If these users have talked before, the auto-generated conversationId is the same, meaning TalkJS will load the pre-existing conversation and all previous messages. Otherwise, it creates a new conversation.

Adding the UI

At this point, everything is set up to allow our users to chat. All we need is a user interface.

TalkJS offers multiple UIs out of the box for your project. This guide uses the chatbox, but the other UIs work the same way.

Create a new chatbox and select the conversation we made earlier. This tells the UI which conversation it should display.

JavaScript
// After creating the conversation
const chatbox = session.createChatbox();
chatbox.select(conversation);

To display our chatbox on the page, we need to mount it on an HTML element. We will create a div element and store it in a variable using bind:this:

<script>
/* ... */
let chatboxEl;
/* ... */
</script>
<div bind:this={chatboxEl} />

Now we can pass that reference to chatbox.mount, which displays the chatbox UI inside our div:

// After chatbox.select
chatbox.mount(this.chatboxEl);

Check your browser, and you should see a fully-featured chat window running in your app. Try sending Jessica a message, and have a play around with TalkJS!

If you don't see the chat window, make sure that you entered your App ID, replacing YOUR_APP_ID in the code.

Next Steps

In this short guide, you've taken your Svelte app to the next level with powerful user-to-user chat. You also learned more about the fundamentals of TalkJS, and how it all fits together. Most importantly, you've built a starting point to try out all the features TalkJS offers.

You might notice that most of your code is sat inside onMount. That's a little bit clunky, and prevents you from using reactive statements. To make is easier to use reactive statements, we recommend wrapping the Talk.ready promise in a component. For more information, check out a more advanced Svelte example.

But what's next? It's time to start playing around with some features! You could create a group chat by adding more users, create a new UI theme, or even enable email notifications - the sky's the limit.