2020-04-07 04:22:57 +00:00
|
|
|
import { ServerContext } from '@/state/server';
|
|
|
|
import { useEffect, useRef } from 'react';
|
2021-01-31 02:43:46 +00:00
|
|
|
import { SocketEvent } from '@/components/server/events';
|
2020-04-07 04:22:57 +00:00
|
|
|
|
2021-01-31 02:43:46 +00:00
|
|
|
const useWebsocketEvent = (event: SocketEvent, callback: (data: string) => void) => {
|
2022-11-25 20:25:03 +00:00
|
|
|
const { connected, instance } = ServerContext.useStoreState(state => state.socket);
|
2020-04-07 04:22:57 +00:00
|
|
|
const savedCallback = useRef<any>(null);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
savedCallback.current = callback;
|
2022-06-26 19:13:52 +00:00
|
|
|
}, [callback]);
|
2020-04-07 04:22:57 +00:00
|
|
|
|
|
|
|
return useEffect(() => {
|
2021-01-31 02:43:46 +00:00
|
|
|
const eventListener = (event: SocketEvent) => savedCallback.current(event);
|
2020-04-07 04:22:57 +00:00
|
|
|
if (connected && instance) {
|
|
|
|
instance.addListener(event, eventListener);
|
|
|
|
}
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
instance && instance.removeListener(event, eventListener);
|
|
|
|
};
|
2022-06-26 19:13:52 +00:00
|
|
|
}, [event, connected, instance]);
|
2020-04-07 04:22:57 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
export default useWebsocketEvent;
|