mirror of
https://github.com/CompassConnections/Compass.git
synced 2026-02-24 19:06:37 -05:00
* Test * Add pretty formatting * Fix Tests * Fix Tests * Fix Tests * Fix * Add pretty formatting fix * Fix * Test * Fix tests * Clean typeckech * Add prettier check * Fix api tsconfig * Fix api tsconfig * Fix tsconfig * Fix * Fix * Prettier
28 lines
874 B
TypeScript
28 lines
874 B
TypeScript
import {useEffect} from 'react'
|
|
import {getWebsocketUrl} from 'common/api/utils'
|
|
import {ServerMessage} from 'common/api/websockets'
|
|
import {APIRealtimeClient} from 'common/api/websocket-client'
|
|
|
|
const client = typeof window !== 'undefined' ? new APIRealtimeClient(getWebsocketUrl()) : undefined
|
|
|
|
export type SubscriptionOptions = {
|
|
topics: string[]
|
|
onBroadcast: (msg: ServerMessage<'broadcast'>) => void
|
|
onError?: (err: Error) => void
|
|
enabled?: boolean
|
|
}
|
|
|
|
export function useApiSubscription(opts: SubscriptionOptions) {
|
|
useEffect(() => {
|
|
const ws = client
|
|
if (ws != null) {
|
|
if (opts.enabled ?? true) {
|
|
ws.subscribe(opts.topics, opts.onBroadcast).catch(opts.onError)
|
|
return () => {
|
|
ws.unsubscribe(opts.topics, opts.onBroadcast).catch(opts.onError)
|
|
}
|
|
}
|
|
}
|
|
}, [opts.enabled, JSON.stringify(opts.topics)])
|
|
}
|