Files
trumpsignal-frontend/lib/useRealtimeData.ts
T
2026-04-21 19:32:53 +08:00

54 lines
1.4 KiB
TypeScript

'use client'
import { useEffect, useRef, useCallback } from 'react'
const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8000'
type PriceUpdate = { type: 'price'; asset: 'BTC' | 'ETH'; price: number }
type PostUpdate = { type: 'new_post'; post: object }
type WsMessage = PriceUpdate | PostUpdate
interface Handlers {
onPrice?: (asset: 'BTC' | 'ETH', price: number) => void
onNewPost?: (post: object) => void
}
export function usePriceSocket(handlers: Handlers) {
const wsRef = useRef<WebSocket | null>(null)
const handlersRef = useRef(handlers)
handlersRef.current = handlers
const connect = useCallback(() => {
const ws = new WebSocket(`${WS_URL}/ws/prices`)
wsRef.current = ws
ws.onmessage = (e) => {
try {
const msg: WsMessage = JSON.parse(e.data)
if (msg.type === 'price' && handlersRef.current.onPrice) {
handlersRef.current.onPrice(msg.asset, msg.price)
} else if (msg.type === 'new_post' && handlersRef.current.onNewPost) {
handlersRef.current.onNewPost(msg.post)
}
} catch (err) {
console.warn('[WS] malformed message:', e.data, err)
}
}
ws.onclose = () => {
setTimeout(connect, 3000)
}
ws.onerror = () => {
ws.close()
}
}, [])
useEffect(() => {
connect()
return () => {
wsRef.current?.close()
}
}, [connect])
}