multica/apps/web/app/hooks/use-gateway.ts
Naiyuan Qing 716bbceaf4 refactor(chat, hooks): simplify handleSend and update useDeviceId to use useSyncExternalStore
- Simplified handleSend function in Chat component by removing unnecessary useCallback.
- Refactored useDeviceId hook to utilize useSyncExternalStore for better state management and removed useState and useEffect for device ID retrieval.
- Updated useGateway hook to ensure onMessageRef is set correctly on options change.
- Enhanced useScrollFade hook to properly cancel animation frames on cleanup.
2026-01-30 23:38:10 +08:00

44 lines
1.2 KiB
TypeScript

import { useEffect, useRef, useState, useCallback } from "react"
import { GatewayClient, type ConnectionState, type RoutedMessage } from "@multica/sdk"
import { useDeviceId } from "./use-device-id"
import { GATEWAY_URL } from "../lib/config"
interface UseGatewayOptions {
onMessage?: (msg: RoutedMessage) => void
}
export function useGateway(options?: UseGatewayOptions) {
const deviceId = useDeviceId()
const [state, setState] = useState<ConnectionState>("disconnected")
const clientRef = useRef<GatewayClient | null>(null)
const onMessageRef = useRef(options?.onMessage)
useEffect(() => {
onMessageRef.current = options?.onMessage
})
useEffect(() => {
if (!deviceId) return
const client = new GatewayClient({
url: GATEWAY_URL,
deviceId,
deviceType: "client",
})
.onStateChange(setState)
.onMessage(msg => onMessageRef.current?.(msg))
clientRef.current = client
client.connect()
return () => { client.disconnect() }
}, [deviceId])
const send = useCallback(
(to: string, action: string, payload: unknown) => {
clientRef.current?.send(to, action, payload)
},
[]
)
return { state, send }
}