-
Notifications
You must be signed in to change notification settings - Fork 296
Expand file tree
/
Copy pathuseCreateChatClient.ts
More file actions
57 lines (48 loc) · 1.42 KB
/
useCreateChatClient.ts
File metadata and controls
57 lines (48 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { useEffect, useState } from 'react';
import { StreamChat } from 'stream-chat';
import type {
OwnUserResponse,
StreamChatOptions,
TokenOrProvider,
UserResponse,
} from 'stream-chat';
/**
* React hook to create, connect and return `StreamChat` client.
*/
export const useCreateChatClient = ({
apiKey,
options,
tokenOrProvider,
userData,
}: {
apiKey: string;
tokenOrProvider: TokenOrProvider;
userData: OwnUserResponse | UserResponse;
options?: StreamChatOptions;
}) => {
const [chatClient, setChatClient] = useState<StreamChat | null>(null);
const [cachedUserData, setCachedUserData] = useState(userData);
if (userData.id !== cachedUserData.id) {
setCachedUserData(userData);
}
const [cachedOptions] = useState(options);
useEffect(() => {
const client = new StreamChat(apiKey, undefined, cachedOptions);
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, cachedOptions, tokenOrProvider]);
return chatClient;
};