2

Always when I try to join a Group Channel, I am presented with this error

code: 800101
message: "Connection should be made first."
name: "SendBirdException"

Here is my code for connecting to Group Channel.

I am connecting to the SendBird with connect in another function async, and only then calling the connectToChat

The group is created by another user, and this is the code for when a user tries to join that group.

User Connection works fine. Group retrieval works fine.

But when I try to connect to the group, it errors out.

public connectToChat(chatId: string) {
  return new Promise((s, e) => {
    const sendBirdEngine = SendBird.getInstance();

    try {
      if (ChatService.isReady) {
        this.log("Connecting to chat...", chatId);

        sendBirdEngine.GroupChannel.getChannel(
          chatId,
          (groupChannel, error) => {
            if (error) {
              this.logError(
                "An error occured while getting channel",
                chatId,
                error
              );
              return;
            }

            this.log("Got the channel!", chatId, groupChannel);

            if (groupChannel.isPublic) {
              groupChannel.join((response, err) => {
                this.log(
                  "groupChannel Join",
                  response
                  // Always getting error here
                );

                if (err) {
                  this.logError("connectToChat", err);
                  e(false);
                  return;
                } else {
                  s(true);

                  this.log("Joined the Chat!", chatId);
                }

                ChatService.chatRooms[
                  chatId
                ] = groupChannel;

                this.log(
                  "Successfully Cached the Channel",
                  chatId
                );
              });
            } else {
              this.logError("[ERROR] Channel is Private");
            }

            // s(true);
          }
        );
      } else {
        this.logError("[ERROR] Chat Service is not ready");
      }
    } catch (err) {
      e(err);
    }
  });
}

EDIT: Added Full Class File for complete reference

class ChatService {
  public static userId: string;

  public static chatRooms: {
    [index: string]: SendBird.BaseChannel;
  } = {};

  private static isReady: boolean = false;

  constructor(userId ? : string) {
    if (userId && !ChatService.userId) {
      ChatService.userId = userId;
    } else {
      this.log("userId already set", ChatService.userId);
    }
  }

  /**
   * create
   */
  public create() {
    return new Promise((s, e) => {
      if (!ChatService.isReady) {
        // connecting to sendbird here
        const sendBirdEngine = new SendBird({
          appId: "XXXXX-XXXXXX-XXXXXX",
        });

        this.log("Engine Initialised!", sendBirdEngine);

        // init the user
        this.initialiseUser((data: any) => {
          s(data);
        });
      }
    });
  }

  /**
   * initialise
   */
  public async initialiseUser(onReadyHandler: any) {
    const userId = ChatService.userId;

    this.log("Starting ChatService", userId);

    try {
      this.connectUserToEngine((res: any) => {
        this.log("connectUser() callback", res);
        ChatService.isReady = true;
        // this.getListOfChatRooms();
        onReadyHandler(true);
      });
    } catch (err) {
      onReadyHandler(false);
      this.log("[ChatService Error]", err);
    }
  }

  /**
   * connects user to engine
   */
  public connectUserToEngine(callback: any) {
    const sendBirdEngine = SendBird.getInstance();
    const userId = ChatService.userId;

    this.log("Connecting user...", userId);

    sendBirdEngine.connect(userId, (user: any, error: any) => {
      if (error) {
        this.log("[Error]", error);
        this.log("Reconnecting User in 5 seconds...");
        setTimeout(() => {
          this.connectUserToEngine(callback);
        }, 5000);
        return;
      } else {
        this.log("User Connected", user);
        callback(user);
      }
    });
  }

  /**
   * connect to a particular chat
   */
  public connectToChat(chatId: string, onNewMessageListener: any) {
    return new Promise((s, e) => {
      const sendBirdEngine = SendBird.getInstance();

      this.log("Current User", sendBirdEngine.currentUser);

      try {
        if (ChatService.isReady) {
          this.log("Connecting to chat...", chatId);

          // this.connectUserToEngine(() => {
          sendBirdEngine.GroupChannel.getChannel(
            chatId,
            (groupChannel, error) => {
              if (error) {
                this.logError(
                  "An error occured while getting channel",
                  chatId,
                  error
                );
                return;
              }

              this.log("Got the channel!", chatId, groupChannel);

              if (groupChannel.isPublic) {
                groupChannel.join((response, err) => {
                  this.log(
                    "groupChannel Join",
                    response
                    // err
                  );

                  // FIXME: Assuming it always works

                  if (err) {
                    this.logError("connectToChat", err);
                    e(false);
                    return;
                  } else {
                    s(true);

                    this.log("Joined the Chat!", chatId);
                  }

                  ChatService.chatRooms[
                    chatId
                  ] = groupChannel;

                  this.log(
                    "Successfully Cached the Channel",
                    chatId
                  );
                });
              } else {
                this.logError("[ERROR] Channel is Private");
              }
              // s(true);
            }
          );
          // });
        } else {
          this.logError("[ERROR] Chat Service is not ready");
        }
      } catch (err) {
        e(err);
      }
    });
  }

  /**
   * connects to all chat rooms
   */
  public async connectToAllChatRooms(
    chatRooms: string[],
    onNewMessageListener: any
  ) {
    try {
      this.log("connectToAllChatRooms()", chatRooms);

      // connect to all chat rooms
      for (const chatRoom of chatRooms) {
        const x = await this.connectToChat(
          chatRoom,
          onNewMessageListener
        );
      }

      this.log("connectToAllChatRooms() done");

      return true;
    } catch (err) {
      this.logError("connectToAllChatRooms", err);
      throw new Error(err);
    }
  }

  export default ChatService;
Sai Datta
  • 895
  • 1
  • 9
  • 25

1 Answers1

0

I took a look at your code. You ChatService class might need a little change.

Idea 1

On the ChatService class you have a create() method that is not returning a promise, if a user already exists.

   public create() {
    return new Promise((s, e) => {
      if (!ChatService.isReady) {
        // connecting to sendbird here
        const sendBirdEngine = new SendBird({
          appId: "APP_ID"
        });
        this.log("Engine Initialised!", sendBirdEngine);
        // init the user
        this.initialiseUser((data: any) => {
          s(data);
        });
      } else {
      // Resolve promise when user already exists
        s("Already Connected!");
      }
    });
  }

From there it seems to work as expected. Correct me if I'm wrong but this is how I implement your class.

const initChat = () => {
  const url = "CHANNEL_URL";
  const chat = new ChatService("USER_ID");
  chat.create().then(res => {
    chat.connectToChat(url).then((res)=>{
      console.log("DONE", res)
    })
  });
};

Idea 2

Also: Perhaps check to see if you are calling

sendBirdEngine.GroupChannel.getChannel()

Before the connection to the user has completed.

Example

Here is a working example of your code if needed. It needs:

  • index.js - CHANNEL_URL and USER_ID
  • ChatService.ts - APP_ID
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jason Allshorn
  • 1,625
  • 1
  • 18
  • 27