Spaces:
Sleeping
Sleeping
File size: 2,126 Bytes
149698e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | 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);
};
}, []);
}
|