From e08656592f635f25dc7f94bd1e6ec02c6d4c31d2 Mon Sep 17 00:00:00 2001 From: Anton Arnautov <43254280+arnautov-anton@users.noreply.github.com> Date: Fri, 1 Mar 2024 13:21:48 +0100 Subject: [PATCH] feat: introduce useCreateChatClient hook (#1916) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### 🎯 Goal Introduce `useCreateChatClient` hook which takes care of creation and initiation of `StreamChat` client. closes: GetStream/stream-chat-react-issues#19 --- .../Chat/hooks/useCreateChatClient.ts | 51 +++++++++++++++++++ src/components/Chat/index.ts | 1 + 2 files changed, 52 insertions(+) create mode 100644 src/components/Chat/hooks/useCreateChatClient.ts 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';