-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
31 lines (27 loc) · 817 Bytes
/
index.js
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
import { useEffect, useRef, useState } from "react";
const instance = new EventTarget();
export const useGetInstance = () => {
return instance;
};
export const useSetValue = (str) => {
const instance = useGetInstance();
return (obj) => {
instance.dispatchEvent(new CustomEvent(str, { detail: obj }));
};
};
export const useGetValue = (str) => {
const instance = useGetInstance();
const refValue = useRef(null);
const [state, setState] = useState(null);
refValue.current = state;
const callback = (currentEvent) => {
setState(currentEvent.detail);
};
useEffect(() => {
instance.addEventListener(str, callback);
return () => {
instance.removeEventListener(str, callback);
};
}, []);
return refValue.current;
};