50 lines
1.5 KiB
TypeScript
50 lines
1.5 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { socketService, DriverLocationUpdate } from '@services';
|
|
|
|
export function useOrderTracking(orderId: string, userJwtToken: string | null) {
|
|
const [driverLocation, setDriverLocation] =
|
|
useState<DriverLocationUpdate | null>(null);
|
|
const [orderStatus, setOrderStatus] = useState<string | null>(null);
|
|
|
|
useEffect(() => {
|
|
if (!orderId || !userJwtToken) {
|
|
return;
|
|
}
|
|
|
|
console.log(`[useOrderTracking] Connecting socket for orderId: ${orderId}`);
|
|
socketService.connect(userJwtToken);
|
|
socketService.joinOrderTracking(orderId);
|
|
|
|
const handleDriverLocationUpdate = (data: DriverLocationUpdate) => {
|
|
console.log('[useOrderTracking] handleDriverLocationUpdate:', data);
|
|
if (data.orderId === orderId) {
|
|
setDriverLocation(data);
|
|
}
|
|
};
|
|
|
|
const handleOrderStatusUpdate = (data: any) => {
|
|
if (data.orderId === orderId) {
|
|
setOrderStatus(data.status);
|
|
if (data.status === 'DELIVERED') {
|
|
console.log(
|
|
'[useOrderTracking] Order delivered. Disconnecting socket.',
|
|
);
|
|
socketService.disconnect(orderId);
|
|
}
|
|
}
|
|
};
|
|
|
|
socketService.onDriverLocationUpdate(handleDriverLocationUpdate);
|
|
socketService.onOrderStatusUpdate(handleOrderStatusUpdate);
|
|
|
|
return () => {
|
|
console.log(
|
|
`[useOrderTracking] Cleaning up tracking socket for orderId: ${orderId}`,
|
|
);
|
|
socketService.disconnect(orderId);
|
|
};
|
|
}, [orderId, userJwtToken]);
|
|
|
|
return { driverLocation, orderStatus };
|
|
}
|