{"version":3,"file":"useCreateChatClient.mjs","names":[],"sources":["../../../../../src/components/Chat/hooks/useCreateChatClient.ts"],"sourcesContent":["import { useEffect, useState } from 'react';\n\nimport { StreamChat } from 'stream-chat';\n\nimport type {\n  ClientUser,\n  DeepPartial,\n  InstanceConfigTree,\n  TokenOrProvider,\n} from 'stream-chat';\n\n/**\n * Creates a `StreamChat` client and connects the user. Unmounting disconnects it; a change of\n * `apiKey`, `tokenOrProvider` or `userData.id` disconnects it and creates a new client.\n *\n * @param params.apiKey - Stream API key.\n * @param params.config - Client configuration, the tree `client.config.set()` takes. Read only on\n * the first render.\n * @param params.tokenOrProvider - Token or token provider of the user. Compared by reference, so\n * keep it stable across renders.\n * @param params.userData - User to connect. Changes other than `userData.id` are ignored.\n * @returns The client once the user is connected, null before that.\n */\nexport const useCreateChatClient = ({\n  apiKey,\n  config,\n  tokenOrProvider,\n  userData,\n}: {\n  apiKey: string;\n  tokenOrProvider: TokenOrProvider;\n  userData: ClientUser;\n  config?: DeepPartial<InstanceConfigTree>;\n}) => {\n  const [chatClient, setChatClient] = useState<StreamChat | null>(null);\n  const [cachedUserData, setCachedUserData] = useState(userData);\n\n  if (userData.id !== cachedUserData.id) {\n    setCachedUserData(userData);\n  }\n\n  const [cachedConfig] = useState(config);\n\n  useEffect(() => {\n    const client = new StreamChat(apiKey, cachedConfig);\n    let didUserConnectInterrupt = false;\n\n    const connectionPromise = client\n      .connectUser(cachedUserData, tokenOrProvider)\n      .then(() => {\n        if (!didUserConnectInterrupt) setChatClient(client);\n      });\n\n    return () => {\n      didUserConnectInterrupt = true;\n      setChatClient(null);\n      connectionPromise\n        .then(() => client.disconnectUser())\n        .then(() => {\n          console.log(`Connection for user \"${cachedUserData.id}\" has been closed`);\n        });\n    };\n  }, [apiKey, cachedUserData, cachedConfig, tokenOrProvider]);\n\n  return chatClient;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAuBA,IAAa,uBAAuB,EAClC,QACA,QACA,iBACA,eAMI;CACJ,MAAM,CAAC,YAAY,iBAAiB,SAA4B,IAAI;CACpE,MAAM,CAAC,gBAAgB,qBAAqB,SAAS,QAAQ;CAE7D,IAAI,SAAS,OAAO,eAAe,IACjC,kBAAkB,QAAQ;CAG5B,MAAM,CAAC,gBAAgB,SAAS,MAAM;CAEtC,gBAAgB;EACd,MAAM,SAAS,IAAI,WAAW,QAAQ,YAAY;EAClD,IAAI,0BAA0B;EAE9B,MAAM,oBAAoB,OACvB,YAAY,gBAAgB,eAAe,CAAC,CAC5C,WAAW;GACV,IAAI,CAAC,yBAAyB,cAAc,MAAM;EACpD,CAAC;EAEH,aAAa;GACX,0BAA0B;GAC1B,cAAc,IAAI;GAClB,kBACG,WAAW,OAAO,eAAe,CAAC,CAAC,CACnC,WAAW;IACV,QAAQ,IAAI,wBAAwB,eAAe,GAAG,kBAAkB;GAC1E,CAAC;EACL;CACF,GAAG;EAAC;EAAQ;EAAgB;EAAc;CAAe,CAAC;CAE1D,OAAO;AACT"}