( path: string, onMessage: (event: T) => void, options?: UseWSOptions, )
| 13 | }; |
| 14 | |
| 15 | export 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 | } |
no test coverage detected