Unread count of all messages

Hello is there a way to get the overall number of unread message count in UIKit using React? (I’m using 2.0.2)

I can see that the SDK receives and internally it tracks the number of unread messages it seems it isn’t exposed.

Our goal is to show a red dot badge next to the chat menu in our application if there’s an unread message (the SendbirdProvider is already initialized but the ChannelList is not yet at this point).

Right now I couldn’t come up with a better solution but poll the API every 30 seconds. Also, it might be even better to have a selector for that so the UI could be updated on its change.

// useInterval is Dan Abramov's setInterval as React hook: https://overreacted.io/making-setinterval-declarative-with-react-hooks/
import useInterval from './useInterval'; 

import Sendbird from 'sendbird';
import _ from 'lodash';

const Menu = (props: { sdk: Sendbird.SendBirdInstance }) => {
    const location = useLocation();
    const [unreadCount, setUnreadCount] = useState(0);
    useInterval(async () => {
      if (_.isEmpty(props.sdk)) {
        return;
      }

      const unread = await props.sdk.getTotalUnreadMessageCount();

      setUnreadCount(unread);
    }, 30 * 1000); // every 30 seconds

   return (
     <ChatMenuItem showBadge={unreadCount > 0} />
   );
})

const MenuWithSendbird = withSendBird(Menu, state => ({  sdk: sendBirdSelectors.getSdk(state) }));

@oroce

Just to make sure I understand, you want to display the total number of unread messages across all chats on the chat menu in your application, correct?

Thanks,
Tyler

@Tyler yes, that’s the goal.
Robert

Thanks for that! So while you can’t do it with the UIKit alone, you could implement the Core SDK alongside the UIKit, and utilize the following call to retrieve the number you’re looking for: https://sendbird.com/docs/chat/v3/javascript/guides/group-channel-advanced#2-retrieve-number-of-unread-messages-in-all-channels

You could then use the onChannelChanged() event handler to re-query the number.
A rough example of this could look something like this:

export const getTotalUnreadMessageCount = () => async (dispatch) => {
  try {
    const sb = SendBird.getInstance();
    sb.getTotalUnreadMessageCount((count, error) => {
      if (error) {
        console.log(error);
      }

      console.log(count);
    });
  } catch (err) {
    console.log('getTotalUnreadMessageCount', err);
  }
};

And then your handler would be:

const channelHandler = new sb.ChannelHandler();
channelHandler.onChannelChanged = (channel) => {
    getTotalUnreadMessageCount();
  };

sb.addChannelHandler('ChatWindowHandler', channelHandler);

Awesome. I used the core sdk before, so I’m kinda familiar with it I just wasn’t sure which handler I should use.
This will make our implementation so much cleaner. Thanks for that @Tyler!

Anytime! Should you have any additional questions regarding it, don’t hesitate to reach out.

-Tyler

1 Like