-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathuseCreateChatClient.ts
More file actions
59 lines (49 loc) · 1.45 KB
/
useCreateChatClient.ts
File metadata and controls
59 lines (49 loc) · 1.45 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
58
59
import { useEffect, useRef, 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 userDataRef = useRef(userData);
userDataRef.current = userData;
const optionsRef = useRef(options);
optionsRef.current = options;
useEffect(() => {
const userData = userDataRef.current;
const client = new StreamChat(apiKey, undefined, optionsRef.current);
let didUserConnectInterrupt = false;
const connectionPromise = client.connectUser(userData, tokenOrProvider).then(() => {
if (!didUserConnectInterrupt) {
setChatClient(client);
}
});
return () => {
didUserConnectInterrupt = true;
setChatClient(null);
connectionPromise
.then(() => client.disconnectUser())
.then(() => {
console.log(`Connection for user "${userData.id}" has been closed`);
});
};
// we should recompute the client on user id change
}, [apiKey, userData.id, tokenOrProvider]);
return chatClient;
};