diff --git a/src/components/Chat/hooks/useCreateChatClient.ts b/src/components/Chat/hooks/useCreateChatClient.ts new file mode 100644 index 000000000..1ee297088 --- /dev/null +++ b/src/components/Chat/hooks/useCreateChatClient.ts @@ -0,0 +1,51 @@ +import { useEffect, useState } from 'react'; + +import { + DefaultGenerics, + ExtendableGenerics, + OwnUserResponse, + StreamChat, + TokenOrProvider, + UserResponse, +} from 'stream-chat'; + +/** + * React hook to create, connect and return `StreamChat` client. + */ +export const useCreateChatClient = ({ + apiKey, + tokenOrProvider, + userData, +}: { + apiKey: string; + tokenOrProvider: TokenOrProvider; + userData: OwnUserResponse | UserResponse; +}) => { + const [chatClient, setChatClient] = useState | null>(null); + const [cachedUserData, setCachedUserData] = useState(userData); + + if (userData.id !== cachedUserData.id) { + setCachedUserData(userData); + } + + useEffect(() => { + const client = new StreamChat(apiKey); + let didUserConnectInterrupt = false; + + const connectionPromise = client.connectUser(cachedUserData, tokenOrProvider).then(() => { + if (!didUserConnectInterrupt) setChatClient(client); + }); + + return () => { + didUserConnectInterrupt = true; + setChatClient(null); + connectionPromise + .then(() => client.disconnectUser()) + .then(() => { + console.log(`Connection for user "${cachedUserData.id}" has been closed`); + }); + }; + }, [apiKey, cachedUserData, tokenOrProvider]); + + return chatClient; +}; diff --git a/src/components/Chat/index.ts b/src/components/Chat/index.ts index 295000502..a493ca7ab 100644 --- a/src/components/Chat/index.ts +++ b/src/components/Chat/index.ts @@ -1,3 +1,4 @@ export * from './Chat'; export * from './hooks/useChat'; export * from './hooks/useCustomStyles'; +export * from './hooks/useCreateChatClient';