useWebSocket.ts 978 B

1234567891011121314151617181920212223242526272829303132
  1. import { useEffect } from 'react';
  2. import { WebSocketClient } from '@/api/websocket';
  3. type Handler = (payload: unknown) => void;
  4. interface SharedClient {
  5. connect(): void;
  6. on(event: string, fn: Handler): void;
  7. off(event: string, fn: Handler): void;
  8. }
  9. let sharedClient: SharedClient | null = null;
  10. function getSharedClient(): SharedClient {
  11. if (sharedClient) return sharedClient;
  12. const basePath = (typeof window !== 'undefined' && window.X_UI_BASE_PATH) || '';
  13. sharedClient = new WebSocketClient(basePath) as SharedClient;
  14. return sharedClient;
  15. }
  16. export function useWebSocket(handlers: Record<string, Handler>) {
  17. useEffect(() => {
  18. const client = getSharedClient();
  19. const entries = Object.entries(handlers);
  20. for (const [event, fn] of entries) client.on(event, fn);
  21. client.connect();
  22. return () => {
  23. for (const [event, fn] of entries) client.off(event, fn);
  24. };
  25. // eslint-disable-next-line react-hooks/exhaustive-deps
  26. }, []);
  27. }