Chat / JavaScript
Chat JavaScript v4
Chat JavaScript
Chat
JavaScript
Home
/
Chat
/
JavaScript
/
Local caching
This is the new Docs for Chat SDK v4 for JavaScript. To see the previous Docs, click here.

Message collection

A MessageCollection instance allows you to swiftly create a chat view that includes all data. This page explains how to make a view using the collection.


Initialization

First, create a MessageCollection instance through the createMessageCollection() method. Here, you need to set the message filter to determine the message order and the starting point of the message list in the chat view.

const filter: MessageFilter = new MessageFilter();
const limit = 100;
const startingPoint: number = Date.now();
const collection: MessageCollection = channel.createMessageCollection({
    filter,
    limit,
    startingPoint,
});
collection
    .initialize(MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API)
    .onCacheResult((err: Error, messages: BaseMessage[]) => {
        // Messages are retrieved from the local cache.
        // They might be too outdated or far from the startingPoint.
    })
    .onApiResult((err: Error, messages: BaseMessage[]) => {
        // Messages are retrieved from the Sendbird server through API.
        // According to MessageCollectionInitPolicy.CACHE_AND_REPLACE_BY_API,
        // the existing data source needs to be cleared
        // before adding retrieved messages to the local cache.
    });

Starting point

The startingPoint parameter is the reference point of message retrieval for a chat view. This should be specified as a timestamp.

If you set the value of startingPoint to the current time or Long.MAX_VALUE, messages in the view are retrieved in reverse chronological order, showing messages from the newest to the oldest. If you set the value of startingPoint to the message last read by the current user, messages in the view are fetched in chronological order, starting from the last message seen by the user to the latest message in the channel.

Policy

After initializing a MessageCollection instance through the initialize() method, you need to set MessageCollectionInitPolicy.

MessageCollectionInitPolicy determines how initialization deals with the message data retrieved from the local cache and API calls. Because we only support CACHE_AND_REPLACE_BY_API as of now, messages in the local cache must be cleared prior to adding the messages from the Sendbird server.

PolicyDescription

CACHE_AND_REPLACE_BY_API

Retrieves cached messages from the local cache and then replaces them with the messages pulled from the Sendbird server through API calls.


Pagination

Use the loadPrevious() and loadNext() methods to retrieve messages from the previous page and the next page.

When the loadPrevious() method is called, the Chat SDK first checks whether there're more messages to load from the previous page through the hasPrevious function. The same goes for the loadNext() method.

These methods have to be called during initialization as well.

if (collection.hasPrevious) {
    // Load the previous messages when the scroll
    // reaches the first message in the chat view.
    const messages: BaseMessage[] = await collection.loadPrevious()
}

if (collection.hasNext) {
    // Load the next messages when the scroll
    // reaches the last message in the chat view.
    const messages: BaseMessage[] = collection.loadNext();
}

Message events

Use MessageCollectionEventHandler to determine how the client app reacts to message-related events.

The following table shows possible cases where each event handler can be called.

HandlerCalled when

onMessagesAdded

- A new message is created as a real-time event.
- New messages are fetched through changelog sync.

onMessagesDeleted

- A message is deleted as a real-time event.
- Message deletion is detected during changelog sync.
- The value of the messageFilter setter changes.

onMessagesUpdated

- A message is updated as a real-time event.
- Message update is detected during changelog sync.
- The send status of a pending message changes.

onChannelUpdated

- The channel information that is included in the user's current chat view is updated as a real-time event.
- Channel info update is detected during changelog sync.

onChannelDeleted

- The current channel is deleted as a real-time event.
- Channel deletion is detected during changelog sync.
* In both cases, the entire view should be disposed of.

onHugeGapDetected

- A huge gap is detected through background sync. In this case, you need to dispose of the view and create a new MessageCollection instance.

const handler: MessageCollectionEventHandler = {
    onMessagesAdded: (context: MessageEventContext, channel: GroupChannel, messages: BaseMessage[]) => {
        // Add the messages to your data source.
    },
    onMessagesUpdated: (context: MessageEventContext, channel: GroupChannel, messages: BaseMessage[]) => {
        // Update the messages in your data source.
    },
    onMessagesDeleted: (context: MessageEventContext, channel: GroupChannel, messageIds: number[]) => {
        // Remove the messages from the data source.
    },
    onChannelUpdated: (context: MessageEventContext, channel: GroupChannel) => {
        // Change the chat view with the updated channel information.
    },
    onChannelDeleted: (context: MessageEventContext, channelUrl: string) => {
        // This is called when a channel was deleted. So the current chat view should be cleared.
    },
    onHugeGapDetected: () => {
        // The Chat SDK detects more than 300 messages missing.
    }
};
collection.setMessageCollectionHandler(handler);

Gap

In local caching, a gap refers to a chunk of objects that are created and logged on the Sendbird server but missing from the local cache. Depending on the connection status, the client app could miss message events and new messages stored in the Sendbird server may not reach the Chat SDK in the client app. In such cases, a gap is created.

Small gaps can be filled in through changelog sync. However, if the client app has been disconnected for a while, too big of a gap can be created.

Huge gap

A gap can be created for many reasons, such as when a user has been offline for days. When the user opens the app and is online again, the Chat SDK checks with the Sendbird server to see if there are any new messages. If it detects that more than 300 messages are missing from the local cache compared to the Sendbird server, the Chat SDK determines that there is a huge gap and onHugeGapDetected is called. In this case, the existing MessageCollection instance should be cleared through the dispose() method and a new one must be created for better performance.

Note: To adjust the number of missing messages that result in a call for onHugeGapDetected, contact our support team.


Dispose of the collection

The dispose() method should be called when you need to clear the current chat view. For example, this can be used when the current user leaves the channel or when a new collection has to be created due to a huge gap detected by onHugeGapDetected.

collection.dispose();