DEV Community

Cover image for CometChat Offline Support in React Native
Dima Portenko
Dima Portenko

Posted on

CometChat Offline Support in React Native

When you building mobile chat app you definitely want keep your app usable while phone offline or with poor internet connection. Offline Chat Support is actually top voted feature request for CometChat Sdks. Unfortunately it's not there yet, but luckily there is undocumented functionality which allow you to implement it yourself.

Basically what we need is to store CometChat.BaseMessage as JSON string and restore message from this string back.

There is getRawMessage which return the raw JSON of the message. So to store array of the messages per group to some local storage we will do following

const setMessages = (groupId: string, messages: CometChat.BaseMessage[]) => {
    const rawMessages = messages.map(msg => msg.getRawMessage());
    const serialised = JSON.stringify(rawMessages);
    storage.set(groupId, serialised);
}

Enter fullscreen mode Exit fullscreen mode

And to restore message back we can use CometChatHelper and it's method processMessage which takes rawMessage data and return instance of TextMessage | MediaMessage | CustomMessage | BaseMessage. So to get array of messages from storage back we have to do something like this

const getMessages = (groupId: string) => {
    const serialisedMessages = storage.getString(groupId);
    if (serialisedMessages) {
      const rawMessages = JSON.parse(serialisedMessages) as string[];
      return Promise.all(
        rawMessages.map(rawMsg =>
          CometChat.CometChatHelper.processMessage(rawMsg),
        ),
      );
    }
},
Enter fullscreen mode Exit fullscreen mode

Here is my implementation of MessagesStorage with react-native-mmkv.

import {MMKV} from 'react-native-mmkv';
import {CometChat} from '@cometchat-pro/react-native-chat';

const storage = new MMKV({
  id: 'mmkv-messages-storage',
});

export const MessagesStorage = {
  setMessages: (groupId: string, messages: CometChat.BaseMessage[]) => {
    const rawMessages = messages.map(msg => msg.getRawMessage());
    const serialised = JSON.stringify(rawMessages);
    storage.set(groupId, serialised);
  },

  getMessages: (groupId: string) => {
    const serialisedMessages = storage.getString(groupId);
    if (serialisedMessages) {
      const rawMessages = JSON.parse(serialisedMessages) as string[];
      return Promise.all(
        rawMessages.map(rawMsg =>
          CometChat.CometChatHelper.processMessage(rawMsg),
        ),
      );
    }
  },
};
Enter fullscreen mode Exit fullscreen mode

Now you can enjoy of opening your chat screen with immediate list of messages cached from previous chat open.

Top comments (0)