-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathuseEventSubscribe.ts
35 lines (31 loc) · 1.11 KB
/
useEventSubscribe.ts
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
import bridge, {
VKBridgeEvent,
AnyReceiveMethodName,
} from '@vkontakte/vk-bridge';
import { useCallback, useEffect, DependencyList } from 'react';
/**
* Хук для подписки на событие vk-bridge.
*
* @param {AnyReceiveMethodName} eventName Название события.
* @param {(event: VKBridgeEvent<AnyReceiveMethodName>) => void} callback Коллбэк, вызываемый при наступлении события.
* @param {React.DependencyList} [deps=[]] Зависимости переданного коллбэка. По умолчанию пустой массив.
*/
const useEventSubscribe = (
eventName: AnyReceiveMethodName,
callback: (event: VKBridgeEvent<AnyReceiveMethodName>) => void,
deps: DependencyList = []
): void => {
const eventListener = useCallback(
(event: VKBridgeEvent<AnyReceiveMethodName>) => {
if (event.detail.type === eventName) {
callback(event);
}
},
deps
);
useEffect(() => {
bridge.subscribe(eventListener);
return () => bridge.unsubscribe(eventListener);
}, deps);
};
export { useEventSubscribe };