How to associate the last message with the 1-1 channel list in PUBNUB REACT?

88 Views Asked by At

I have this requirement where i have to populate 1-1 channels on the left side . With the channels list I have to show the last sent message in the channel with each channel . How can I achieve this ?

I thought of a process where i would

  1. Generate the list of joined channels
  2. Fetch the last message of each channel by calling the history api
  3. Then associate the last message with the meta data of the channel
  4. Show it in the view

Is this the better approach or there are any other ways to do it better ?

2

There are 2 best solutions below

0
Darryn Campbell On

Your approach sounds great, I followed similar steps when I put my chat demo together a few months ago: https://github.com/PubNubDevelopers/PubNub-Showcase/tree/main/web/chat. I'll copy the relevant code here:

Generate the list of joined channels

This returns all channel members, you could filter for only channels you are a member of.

    pubnub.objects
          .getChannelMembers({
            channel: channel,
            sort: { updated: 'desc' },
            include: {
              UUIDFields: true
            },
            totalCount: true
          })

Fetch the last message of each channel by calling the history API

    //  Load channel history
            pubnub
              .fetchMessages({
                channels: [channelName],
                count: 20, //  Limit to 20 messages.  Design decision for this app, not a limitation of PubNUb
                includeUUID: true,
                includeMessageActions: true
              })

Then associate the last message with the meta data of the channel

I associated the last read timetoken, but you could associate the last message in the same way

    pubnub.objects.setMemberships({
      channels: [{ id: channel, custom: { lastReadTimetoken: timetoken } }],
      uuid: pubnub.getUserId()
    })
0
Darryn Campbell On

To add to my previous answer, there is now an alternative API from PubNub specifically for Chat: https://www.pubnub.com/docs/chat/chat-sdk/overview

Generate the list of joined channels

const channels = await chat.getChannels()

Fetch the last message of each channel by calling the history API

// reference the "channel" object
const channel = await chat.getChannel("support")
// invoke the "getHistory()" method on the "channel" object
await channel.getHistory(
    {
        startTimetoken: "15343325214676133",
        count: 10
    }
)