How to Create Threads and Quote Messages with the PubNub Chat SDK
Tags: chatsdk, typescriptsdk, chatjavascript
Published: 2023-12-21 10:10:20

Introduction to the PubNub Chat SDK
-----------------------------------

The PubNub Chat SDK, available for TypeScript and JavaScript applications, exposes a set of APIs designed to make it easy to add powerful and flexible chat features to your app with minimum development. Chat options like [quoting](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/quotes), [mentioning users](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/mentions), [channel references](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references), [threads](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads), [read receipts](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/read-receipts), and [typing indicators](https://www.pubnub.com/docs/chat/chat-sdk/build/features/typing-indicator) are supported natively by the SDK, letting you build a full-fledged app quickly.

Please refer to our [documentation](https://www.pubnub.com/docs/chat/chat-sdk/overview) and [sample chat app](https://www.pubnub.com/docs/chat/chat-sdk/build/sample-chat) to get started with the Chat SDK. Our [tutorial](https://www.pubnub.com/tutorials/chat-sdk/) will walk you through the basic functionality of the Chat SDK and touch on some more advanced features whilst our [hosted demo](https://www.pubnub.com/demos/chat-sdk-mobile/) will show the Chat SDK in action.

This how-to is part of a **series of posts** diving into some of the more powerful features of the PubNub Chat SDK. The series can be read in any order, but the list of related articles is below:

-   [How to Manage User Channel Membership with the Chat SDK](https://pubnub.com/how-to/chat-sdk-manage-user-channel-membership/)
-   [How to Add Reactions and Emojis to Messages with the Chat SDK](https://pubnub.com/how-to/chat-sdk-add-reactions-to-messages/)
-   [How to Create Threads and Quote Messages with the Chat SDK](https://pubnub.com/how-to/chat-sdk-create-threads-and-quote-messges/)
-   [How to Mention Users and Channels with the Chat SDK](https://pubnub.com/how-to/chat-sdk-mention-users/)

Create Threads & Quote Messages
-------------------------------

One of the reasons we introduced the PubNub Chat SDK was to address feedback we received from chat developers using our traditional SDKs. Although any of our PubNub SDKs make it trivial to exchange real-time messages between users, we saw many developers needed to implement the same chat features that users had come to expect, features such as organizing messages into threads, quoting a previous message, or tagging other users. With the PubNub Chat SDK, we have taken those standard chat features and exposed APIs to make it easy for you to implement them in your own app; this guide will walk you through how to implement the first two examples, creating a message thread and quoting a previous message.

### Prerequisites

Ensure you have an instance of the [Chat object](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/chat) instantiated in your app

```js
const chat = await Chat.init({
  publishKey: "YOUR_PUBLISH_KEY",
  subscribeKey: "YOUR_SUBSCRIBE_KEY",
  userId: "YOUR_USER_ID",
})
```

There are a lot of possible parameters you can pass to the Chat SDK, but for threads and quotes, you do not need anything more than the standard publish key, subscribe key, and user ID. If all of this is new to you, and you’re not sure where to get started, please check out the [initial configuration](https://www.pubnub.com/docs/chat/chat-sdk/build/configuration) section in our documentation.

### Message Threads

The [documentation for message threads](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads) lives under the Message documentation and will explain some of the implementation details; essentially, each message thread requires its own PubNub channel to handle communication, but that implementation is hidden from you if you are using the Chat SDK.

Given an existing root [Message](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message), you can create a thread from that message using the [createThread()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads#create-thread) API. Since you can only have a single thread for any message, it is best practice to check whether a thread already exists before creating a new one with the [hasThread()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads#utility-getter-function) API

```js
if (!rootMessage.hasThread)
{
  threadChannel = await rootMessage.createThread()
}
```

createThread() will return a [ThreadChannel](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/thread-channel) object with similar methods to [Channel](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/channel). For example, if you wanted to read the entire [history](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads#get-historical-thread-message) of a conversation with threads, the pseudocode might look like this:

```js
FOREACH message in Channel
  message.getHistory()
  IF (message.hasThread() THEN
    threadChannel = message.getThread()
    threadChannel.getHistory()
  END IF
END FOREACH
```

You can send text messages on a thread channel in the same way you sent messages on a standard channel, with the [sendText()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads#send-thread-message) API

```js
const threadChannel = rootMessage.getThread()
threadChannel.sendText(“hello”)
```

### Quoting Messages

Quoting a message is an example of one of our Chat SDK features that provides some context about the message being sent, which the recipient can interpret. Being able to [sendText()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads#send-thread-message) like the previous example is all very good, but what if you want to include a file with your message? What if you want to tag users or channels in your message? Or, most pertinently for this guide, what if you wanted to quote a previous message within the current message? All of these scenarios are handled using a [MessageDraft](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message-draft).

A MessageDraft is a fundamental type in the Chat SDK and will be used by most chat implementations to deliver a feature-rich experience for your users. You will need to create a new MessageDraft object every time a new chat message is composed, then you can call the [addQuote()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/quotes#quote-message) API to reference a previous [message](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message).

The [MessageDraft](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/message-draft) is discussed in more detail in the guide describing [how to mention users and channels](https://pubnub.com/how-to/chat-sdk-mention-users/), but in summary, you would:

Declare a variable to hold the message draft

```js
 const [newMessageDraft, setNewMessageDraft] = useState<MessageDraft>()
```

As part of your chat initialization, and after any message is sent, initialize a new MessageDraft

```js
setNewMessageDraft(threadChannel.createMessageDraft())
```

Whenever your input text changes (i.e. the user types something), notify the message draft

```js
//  Note: Within the onChange() handler for the input field 
const response = await newMessageDraft.onChange(event.currentTarget.value)
```

Add a previous message as a quote in response to a user action

```js
newMessageDraft.addQuote(message)
```

Send the message when required

```js
newMessageDraft.send()
```

This is easier to understand if you see it in a working demo...

### Putting it all together

You can see a very simple example of message threads and quoting messages in the short demo below:

This is a real, live, working demo, so feel free to launch the demo in multiple tabs to see real-time messages being received. Because this is a shared application, ‘Reset App State’ will give you a blank slate to play with.

Interactive Demo
----------------

  
**If the embedded content is not available** on this page, it can also be viewed at [https://chat-sdk-how-to-threads-quotes.netlify.app/](https://chat-sdk-how-to-threads-quotes.netlify.app/)

The code that drives this demo is available on [GitHub](https://github.com/PubNubDevelopers/Chat-SDK-How-Tos/tree/main/threads-quotes), but here are some excerpts from pertinent code in the app showing how it fits together:

```js
//  Input field onChange handler
async function handleInput(event: React.FormEvent<HTMLInputElement>)
{
  //  No special rendering for Message Draft with this app
  if (!newMessageDraft) return
  const response = await newMessageDraft.onChange(event.currentTarget.value)
}
```

The logic to submit a message. This demo is hard-coded to always reply to the thread channel

```js
async function handleSend(event: React.SyntheticEvent) {
  newMessageDraft.send()
  setNewMessageDraft(threadChannel.createMessageDraft())
  setQuotedMessagePreview("")
  setText("")
}
```

The User presses the “Quote Message” button

```js
async function handleQuoteMessage(message: Message)
{
  if (!newMessageDraft) return;
  setQuotedMessagePreview(message.text)
  newMessageDraft.addQuote(message)
}
```

Remember that [you can’t quote a message from another channel](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/quotes#quote-message), so the demo only allows you to quote messages from the same thread.

Demo: Create Threads and Quote Messages with our React Native demo on Mobile
----------------------------------------------------------------------------

You can play with these features using our Chat SDK Demo for Mobile, available as a [hosted demo](https://www.pubnub.com/demos/chat-sdk-mobile/) with complete source code on [GitHub](https://github.com/pubnub/js-chat/tree/master/samples/react-native-group-chat). **You should also see the demo rendered in an iFrame at the bottom of this section**.

![Two smartphones displaying message thread with user interactions in a chat application.](https://images.ctfassets.net/3prze68gbwl1/6Z3UrVL7MjylWg9sPQ3bir/f53ef78f4b17272bb70f5431757c98d4/threads-quotes.png)

Follow these steps to create a thread and quote a message in our demo:

1.  Log into the application, choosing a random user ID for each device.
2.  Start a conversation from the second device, selecting the user logged into the first device.
3.  Add some messages to the conversation
4.  Long press on one of the messages.
5.  Select ‘Reply in thread’ and send a reply
6.  Long press on one of the messages (it could also be the reply you just sent)
7.  Select ‘Quote message’
8.  Send a message containing this quoted text
9.  Notice that if you back out of the conversation or even log out of and back into the app, the reactions are retained and read from the message history.

  
**If the embedded content is not available** on this page, it can also be viewed at [https://pubnubdevelopers.github.io/Chat-SDK-Demo/mobile/](https://pubnubdevelopers.github.io/Chat-SDK-Demo/mobile/)

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://pubnub.com/how-to/chat-sdk-create-threads-and-quote-messges/)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/) for immediate access to PubNub keys for free

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/docs) will get you up and running, regardless of your use case or [SDK](https://www.pubnub.com/docs)