Skip to content

Commit 374ad30

Browse files
authored
Create useChatClient.js
1 parent c562ad2 commit 374ad30

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
// useChatClient.js
2+
3+
import { useEffect, useState } from 'react';
4+
import { StreamChat } from 'stream-chat';
5+
import { chatApiKey, chatUserId, chatUserName, chatUserToken } from './chatConfig';
6+
7+
const user = {
8+
id: chatUserId,
9+
name: chatUserName,
10+
};
11+
12+
const chatClient = StreamChat.getInstance(chatApiKey);
13+
14+
export const useChatClient = () => {
15+
const [clientIsReady, setClientIsReady] = useState(false);
16+
17+
useEffect(() => {
18+
const setupClient = async () => {
19+
try {
20+
chatClient.connectUser(user, chatUserToken);
21+
setClientIsReady(true);
22+
23+
// connectUser is an async function. So you can choose to await for it or not depending on your use case (e.g. to show custom loading indicator)
24+
// But in case you need the chat to load from offline storage first then you should render chat components
25+
// immediately after calling `connectUser()`.
26+
// BUT ITS NECESSARY TO CALL connectUser FIRST IN ANY CASE.
27+
} catch (error) {
28+
if (error instanceof Error) {
29+
console.error(`An error occurred while connecting the user: ${error.message}`);
30+
}
31+
}
32+
};
33+
34+
// If the chat client has a value in the field `userID`, a user is already connected
35+
// and we can skip trying to connect the user again.
36+
if (!chatClient.userID) {
37+
setupClient();
38+
}
39+
}, []);
40+
41+
return {
42+
clientIsReady,
43+
};
44+
};

0 commit comments

Comments
 (0)