For AI agents: Find a documentation index at https://talkjs.com/llms.txt (full content at https://talkjs.com/llms-full.txt). Get a markdown version of any page by appending .md to its URL path.

Filter a conversation list

Show conversations by unread status, time, or custom data.

View as Markdown

Conversation filters let you show a subset of the current user's conversations. For example, you can build an unread view, separate support conversations from other chats, or hide conversations that have no messages yet.

Prerequisites

This guide assumes you've completed the relevant React getting-started guide, and already have an existing user with conversations to display.

The same filter format works with the @talkjs/react-components package and the JavaScript Data API in the @talkjs/core package. For all supported fields and operators, see the filter reference.

Set up a conversation list filter

Pass a conversationFilter prop to an Inbox or ConversationList. For example, show only unread conversations in a React inbox:

import { Inbox } from '@talkjs/react-components';
import '@talkjs/react-components/default.css';

export default function Chat() {
  return (
    <Inbox
      appId="<APP_ID>"
      userId="<USER_ID>"
      conversationFilter={{ isUnread: true }}
      style={{ width: '100%', height: '600px' }}
    />
  );
}

Replace <APP_ID> and <USER_ID> with your app ID and an existing user's ID. Configure authentication before mounting the UI when authentication is enabled.

Filter types

Use any of the following objects as your filter.

Unread conversations

const filter = { isUnread: true };

This includes conversations the user manually marked as unread, even if their unread message count is zero. Use isUnread: false to show only read conversations. As conversations change read state, the filtered list updates automatically.

Time filters

const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
const filter = { lastActivityAt: ['>', sevenDaysAgo] };

lastActivityAt uses the time of the last message, or the current user's join time if the conversation has no messages. Timestamps are Unix timestamps in milliseconds. You can also filter by createdAt or joinedAt.

The cutoff above is calculated once. Recalculate and apply a new filter if you want the seven-day window to advance while your app stays open.

To show conversations created within a specific time range, use between:

const filter = {
  createdAt: ['between', [startTimestamp, endTimestamp]],
};

Replace startTimestamp and endTimestamp with Unix timestamps in milliseconds.

String filters

const filter = { access: ['==', 'ReadWrite'] };

Use Read to select read-only conversations instead.

You can also match the conversation's subject. For example, show conversations with either of two subjects:

const filter = { subject: ['oneOf', ['Welcome', 'Project chat']] };

String filters support ==, !=, oneOf, and !oneOf. Use the filter reference for supported operands.

Conversations with custom data

For example, show conversations whose custom.category is support:

const filter = { custom: { category: ['==', 'support'] } };

The custom field must already be set on the conversation, using the Data API or the REST API. Filtering doesn't create or update custom data.

Match any of several values with oneOf:

const filter = {
  custom: { category: ['oneOf', ['support', 'sales']] },
};

To select conversations where a custom field is present or missing, use exists or !exists:

const filter = { custom: { category: 'exists' } };

Conversations with messages

const filter = { hasMessages: true };

This hides empty conversations. Use hasMessages: false to show only empty conversations.

Combine conditions

Put multiple properties in one object to require all of them. For example, show unread support conversations that have messages:

const filter = {
  isUnread: true,
  hasMessages: true,
  custom: { category: ['==', 'support'] },
};

Use any to match at least one of several filters. For example, show conversations that are unread or belong to the support category:

const filter = [
  'any',
  [
    { isUnread: true },
    { custom: { category: ['==', 'support'] } },
  ],
];

Each object inside any can contain multiple conditions, which must all match within that object.

Change or clear the filter

In React, update the conversationFilter prop. For example, add a button to switch between all and unread conversations:

import { useState } from 'react';
import { Inbox } from '@talkjs/react-components';
import '@talkjs/react-components/default.css';

export default function Chat() {
  const [unreadOnly, setUnreadOnly] = useState(false);

  return (
    <>
      <button onClick={() => setUnreadOnly((value) => !value)}>
        {unreadOnly ? 'Show all conversations' : 'Show unread conversations'}
      </button>
      <Inbox
        appId="<APP_ID>"
        userId="<USER_ID>"
        conversationFilter={unreadOnly ? { isUnread: true } : undefined}
        style={{ width: '100%', height: '600px' }}
      />
    </>
  );
}

Updating the filter creates a new conversation-list subscription. An empty object, {}, also clears the filter.

Filter a Data API subscription

If you're building your own conversation list, pass the filter in the first argument to subscribeConversations:

import { getTalkSession } from '@talkjs/core';

const session = getTalkSession({ appId: '<APP_ID>', userId: '<USER_ID>' });

const subscription = session.subscribeConversations(
  { filter: { isUnread: true } },
  (conversations, loadedAll) => {
    // Render these matching conversation snapshots in your own UI.
    console.log(conversations);
    console.log('All matching conversations loaded:', loadedAll);
  },
);

// When the user requests more conversations:
subscription.loadMore();

// When your view is removed:
subscription.unsubscribe();

The initial subscription loads the most recently active matching conversations. It is paginated: if loadedAll is false, more matching conversations are available through loadMore(). The callback runs again when data changes or more conversations load. The length of a partial page isn't a total count of matching conversations.

To change a Data API filter, unsubscribe from the old subscription and create a new one with the new filter. Call unsubscribe() when your view is removed.

REST API conversation filters

To filter conversations from your backend, use the REST API's filter query parameter. For example, select support conversations by URL-encoding a JSON filter:

curl --get 'https://api.talkjs.com/v1/<APP_ID>/conversations' \
  -H 'Authorization: Bearer <SECRET_KEY>' \
  --data-urlencode 'filter={"custom":{"category":["==","support"]}}'

Run this request on your backend to keep the secret key out of browser code. See the REST API reference for its supported filter fields.