MCPcopy Create free account
hub / github.com/Openpanel-dev/openpanel / useWS

Function useWS

apps/start/src/hooks/use-ws.ts:15–49  ·  view source on GitHub ↗
(
  path: string,
  onMessage: (event: T) => void,
  options?: UseWSOptions,
)

Source from the content-addressed store, hash-verified

13};
14
15export default function useWS<T>(
16 path: string,
17 onMessage: (event: T) => void,
18 options?: UseWSOptions,
19) {
20 const context = useAppContext();
21 const ws = context.apiUrl.replace(/^https/, 'wss').replace(/^http/, 'ws');
22 const [baseUrl, setBaseUrl] = useState(`${ws}${path}`);
23
24 const debouncedOnMessage = useMemo(() => {
25 if (options?.debounce) {
26 return debounce(onMessage, options.debounce.delay, options.debounce);
27 }
28 return onMessage;
29 }, [options?.debounce?.delay]);
30
31 useEffect(() => {
32 if (baseUrl === `${ws}${path}`) return;
33 setBaseUrl(`${ws}${path}`);
34 }, [path, baseUrl, ws]);
35
36 useWebSocket(baseUrl, {
37 shouldReconnect: () => true,
38 onMessage(event) {
39 try {
40 const data = getSuperJson<T>(event.data);
41 if (data !== null && data !== undefined) {
42 debouncedOnMessage(data);
43 }
44 } catch (error) {
45 console.error('Error parsing message', error);
46 }
47 },
48 });
49}

Callers 7

RealtimeReloaderFunction · 0.85
EventListenerFunction · 0.85
BillingFunction · 0.85
CounterWidgetFunction · 0.85
RealtimeWidgetFunction · 0.85
useLiveCounterFunction · 0.85

Calls 2

useAppContextFunction · 0.90
replaceMethod · 0.80

Tested by

no test coverage detected