1
1
mirror of https://github.com/pterodactyl/panel.git synced 2024-11-26 02:52:30 +01:00
Pterodactyl-Panel/resources/scripts/plugins/useWebsocketEvent.ts
2020-07-04 18:30:50 -07:00

25 lines
786 B
TypeScript

import { ServerContext } from '@/state/server';
import { useEffect, useRef } from 'react';
const useWebsocketEvent = (event: string, callback: (data: string) => void) => {
const { connected, instance } = ServerContext.useStoreState(state => state.socket);
const savedCallback = useRef<any>(null);
useEffect(() => {
savedCallback.current = callback;
}, [ callback ]);
return useEffect(() => {
const eventListener = (event: any) => savedCallback.current(event);
if (connected && instance) {
instance.addListener(event, eventListener);
}
return () => {
instance && instance.removeListener(event, eventListener);
};
}, [ event, connected, instance ]);
};
export default useWebsocketEvent;