Spaces:
Sleeping
Sleeping
| import { useEffect, useRef } from 'react'; | |
| import { useQueryClient } from '@tanstack/react-query'; | |
| import { getSocket, connectSocket } from '../services/websocket'; | |
| export function useRealtime() { | |
| const queryClient = useQueryClient(); | |
| useEffect(() => { | |
| connectSocket(); | |
| const socket = getSocket(); | |
| const onNewTx = () => { | |
| queryClient.invalidateQueries({ queryKey: ['transactions'] }); | |
| queryClient.invalidateQueries({ queryKey: ['transactionStats'] }); | |
| }; | |
| const onScanDone = () => { | |
| queryClient.invalidateQueries({ queryKey: ['transactions'] }); | |
| queryClient.invalidateQueries({ queryKey: ['transactionStats'] }); | |
| queryClient.invalidateQueries({ queryKey: ['scanHistory'] }); | |
| }; | |
| socket.on('transaction:new', onNewTx); | |
| socket.on('scan:completed', onScanDone); | |
| return () => { | |
| socket.off('transaction:new', onNewTx); | |
| socket.off('scan:completed', onScanDone); | |
| // Don't disconnect — socket is shared and other hooks may still need it | |
| }; | |
| }, [queryClient]); | |
| } | |
| export function useScanEvents(callbacks?: { | |
| onStarted?: (data: any) => void; | |
| onProgress?: (data: any) => void; | |
| onCompleted?: (data: any) => void; | |
| onError?: (data: any) => void; | |
| }) { | |
| const callbacksRef = useRef(callbacks); | |
| callbacksRef.current = callbacks; | |
| useEffect(() => { | |
| const socket = getSocket(); | |
| if (!socket.connected) connectSocket(); | |
| const onStarted = (data: any) => callbacksRef.current?.onStarted?.(data); | |
| const onProgress = (data: any) => callbacksRef.current?.onProgress?.(data); | |
| const onCompleted = (data: any) => callbacksRef.current?.onCompleted?.(data); | |
| const onError = (data: any) => callbacksRef.current?.onError?.(data); | |
| socket.on('scan:started', onStarted); | |
| socket.on('scan:progress', onProgress); | |
| socket.on('scan:completed', onCompleted); | |
| socket.on('scan:error', onError); | |
| return () => { | |
| socket.off('scan:started', onStarted); | |
| socket.off('scan:progress', onProgress); | |
| socket.off('scan:completed', onCompleted); | |
| socket.off('scan:error', onError); | |
| }; | |
| }, []); | |
| } | |