xmtp / xmtp-react-native

A package you can use to build with XMTP in a React Native or Expo app.
MIT License
41 stars 19 forks source link

Feature request: Fetch all conversation ordered by timestamp #175

Closed WilliamYWY closed 10 months ago

WilliamYWY commented 10 months ago

Is your feature request related to a problem?

Is there a way to retrieve conversations that are ordered based on the time of their last received message? Or include the timestamp of the last received message in the object? Thanks!

Describe the solution to the problem

Provide the timestamp of the last received message received by each conversation in the object.

Describe the uses cases for the feature

List the conversation based on the latest activity

Additional details

No response

fabriguespe commented 10 months ago

In XMTP, there isn't a direct way to retrieve conversations ordered by the time of their last received message or include the timestamp of the last received message in the conversation object. This is due to XMTP's commitment to privacy.

This means that an app must fetch all conversations up front, which might seem inefficient, especially for accounts with thousands of conversations. However, to mitigate this, apps built with XMTP should adopt a local-first cache architecture. This approach significantly speeds up subsequent app loads, turning the initial delay into a one-time occurrence and enhancing the overall user experience.

For now, because there is no server-side filtering you would need to fetch all the conversations and then go through the messages sorting by timestamp

// Fetch all conversations
const conversations = await client.conversations.list();

// Fetch the most recent message for each conversation
const conversationsWithLastMessage = await Promise.all(
  conversations.map(async (conversation) => {
    const messages = await conversation.messages();
    return {
      ...conversation,
      lastMessage: messages[0],
    };
  })
);

// Sort conversations by the timestamp of the most recent message
const sortedConversations = conversationsWithLastMessage.sort(
  (a, b) => b.lastMessage.sent - a.lastMessage.sent
);

We are currently working on making all of our SDKs local cache first!