-
Notifications
You must be signed in to change notification settings - Fork 296
Expand file tree
/
Copy pathuseSelectedChannelState.ts
More file actions
49 lines (42 loc) · 1.39 KB
/
useSelectedChannelState.ts
File metadata and controls
49 lines (42 loc) · 1.39 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
import { useCallback } from 'react';
import { useSyncExternalStore } from 'use-sync-external-store/shim';
import type { Channel, EventTypes } from 'stream-chat';
// eslint-disable-next-line @typescript-eslint/no-empty-function
const noop = () => {};
export function useSelectedChannelState<O>(_: {
channel: Channel;
selector: (channel: Channel) => O;
stateChangeEventKeys?: EventTypes[];
}): O;
export function useSelectedChannelState<O>(_: {
selector: (channel: Channel) => O;
channel?: Channel | undefined;
stateChangeEventKeys?: EventTypes[];
}): O | undefined;
export function useSelectedChannelState<O>({
channel,
selector,
stateChangeEventKeys = ['all'],
}: {
selector: (channel: Channel) => O;
channel?: Channel;
stateChangeEventKeys?: EventTypes[];
}): O | undefined {
const subscribe = useCallback(
(onStoreChange: (value: O) => void) => {
if (!channel) return noop;
const subscriptions = stateChangeEventKeys.map((et) =>
channel.on(et, () => {
onStoreChange(selector(channel));
}),
);
return () => subscriptions.forEach((subscription) => subscription.unsubscribe());
},
[channel, selector, stateChangeEventKeys],
);
const getSnapshot = useCallback(() => {
if (!channel) return undefined;
return selector(channel);
}, [channel, selector]);
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}