1

I'm facing an issue with initializing CometChat in a React application.

The error I'm getting is:

Error: Cannot find name 'setCometChat'. Did you mean 'CometChat'?
'CometChat' is declared here.

I have a useEffect for initialization:

useEffect(() => {
  initCometChat();
  // ...
}, []);

And here's the initCometChat function:

const initCometChat = async () => {
  const { CometChat } = await import('@cometchat-pro/cordova-ionic-chat');
  const appID = `${process.env.REACT_APP_COMETCHAT_APP_ID}`;
  const region = `${process.env.REACT_APP_COMETCHAT_REGION}`;
  const appSetting = new CometChat.AppSettingsBuilder().subscribePresenceForAllUsers().setRegion(region).build();
  CometChat.init(appID, appSetting).then(
    () => {
      console.log('CometChat was initialized successfully');
      setCometChat(() => CometChat);
    },
    error => {
    }
  );
};

I tried using the passed-in setter function like this:

setCometChat(CometChat);

But it's not working.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
Artem
  • 23
  • 3

1 Answers1

2

Not familiar with Ionic, but if I get it right, you are trying to set the current instance of CometChat to the variable CometChat that you have been using to initialize one. I suppose the error is occurring because CometChat has not been initialized as a state using useState() hook.

But in this case, setting the CometChat state to the variable CometChat that you use to initialize should not work. Maybe try separating the one that you are initializing and CometChat itself. What I mean is something like:

import React, { useState, useEffect } from 'react';

function Component() {
  const [cometChatInitialized, setCometChatInitialized] = useState(null);

  const initCometChat = async () => {
    const { CometChat } = await import('@cometchat-pro/cordova-ionic-chat');
    // ...

    CometChat.init(appID, appSetting).then(
      () => {
        console.log('CometChat was initialized successfully');
        setCometChatInitialized(CometChat);
      },
      // ...
    );
  };
}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
dummyjuice
  • 40
  • 4
  • 1
    Creating separate sections for the text makes the answer much easier to read. You can divide into sections by putting a an empty line between the sections (press enter key twice). – Maarten Bodewes Aug 20 '23 at 21:19