mirror of
https://github.com/CompassConnections/Compass.git
synced 2026-01-06 12:57:51 -05:00
31 lines
892 B
TypeScript
31 lines
892 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)])
|
|
}
|