Skip to content

Commit

Permalink
feat: introduce useCreateChatClient hook (#1916)
Browse files Browse the repository at this point in the history
### 🎯 Goal

Introduce `useCreateChatClient` hook which takes care of creation and
initiation of `StreamChat` client.

closes: GetStream/stream-chat-react-issues#19
  • Loading branch information
arnautov-anton committed Mar 1, 2024
1 parent b051698 commit e086565
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
51 changes: 51 additions & 0 deletions src/components/Chat/hooks/useCreateChatClient.ts
Original file line number Diff line number Diff line change
@@ -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 = <SCG extends ExtendableGenerics = DefaultGenerics>({
apiKey,
tokenOrProvider,
userData,
}: {
apiKey: string;
tokenOrProvider: TokenOrProvider;
userData: OwnUserResponse<SCG> | UserResponse<SCG>;
}) => {
const [chatClient, setChatClient] = useState<StreamChat<SCG> | null>(null);
const [cachedUserData, setCachedUserData] = useState(userData);

if (userData.id !== cachedUserData.id) {
setCachedUserData(userData);
}

useEffect(() => {
const client = new StreamChat<SCG>(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;
};
1 change: 1 addition & 0 deletions src/components/Chat/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './Chat';
export * from './hooks/useChat';
export * from './hooks/useCustomStyles';
export * from './hooks/useCreateChatClient';

0 comments on commit e086565

Please sign in to comment.