From 87385f6ace3e464da80291a74812b833ec92f2ea Mon Sep 17 00:00:00 2001 From: Jonas Geertsen Lund Date: Thu, 7 Nov 2024 09:51:38 +0100 Subject: [PATCH] Update path on duration change (initial) --- src/components/vesselDetailsBox.tsx | 60 +++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 17 deletions(-) diff --git a/src/components/vesselDetailsBox.tsx b/src/components/vesselDetailsBox.tsx index 6964672..e9a5827 100644 --- a/src/components/vesselDetailsBox.tsx +++ b/src/components/vesselDetailsBox.tsx @@ -13,44 +13,68 @@ export default function VesselDetailsBox() { const [pathDuration, setPathDuration] = useState(1) const [isCollapsed, setIsCollapsed] = useState(false) + // Fetch vessel details on selected vessel change useEffect(() => { const fetchDetails = async () => { if (!selectedVesselmmsi) return - const details = await clientHandler.getVesselInfo({ - mmsi: selectedVesselmmsi, - timestamp: myDateTimeRef.current.getTime(), - }) - setVesselDetails(details) + + try { + const details = await clientHandler.getVesselInfo({ + mmsi: selectedVesselmmsi, + timestamp: myDateTimeRef.current.getTime(), + }) + setVesselDetails(details) + } catch (e) { + console.error(e) + } } fetchDetails() setLoading(false) }, [clientHandler, selectedVesselmmsi]) - async function controlVesselPath() { + async function tryGetVesselPath() { if (!selectedVesselmmsi) return - if (selectedVesselPath.length > 0) { + try { + const res = await clientHandler.getVesselPath({ + mmsi: selectedVesselmmsi, + endtime: myDateTimeRef.current.getTime() / 1000, + starttime: myDateTimeRef.current.getTime() / 1000 - pathDuration * 60 * 60, + }) //time is in seconds + setSelectedVesselPath(res.pathHistory.locations) + } catch (e) { + console.error(e) + } + } + + const pathIsShown = selectedVesselPath.length > 0 + + async function controlVesselPath() { + if (pathIsShown) { setSelectedVesselPath([]) return } - const res = await clientHandler.getVesselPath({ - mmsi: selectedVesselmmsi, - endtime: myDateTimeRef.current.getTime() / 1000, - starttime: myDateTimeRef.current.getTime() / 1000 - pathDuration * 60 * 60, - }) //time is in seconds - setSelectedVesselPath(res.pathHistory.locations) + await tryGetVesselPath() } - function handleDurationChange(val: string) { + async function handleDurationChange(val: string) { try { const parsed = parseFloat(val) - setPathDuration(parsed) + setPathDuration(Math.max(0, parsed)) } catch (e) { console.error(e) setPathDuration(1) } } + // Fetch path history on path duration change + useEffect(() => { + async function doSomething() { + await tryGetVesselPath() + } + if (pathIsShown) doSomething() + }, [pathDuration, pathIsShown, tryGetVesselPath]) + const vesselDetailsContent = [ { displayName: 'Name', value: vesselDetails?.name }, { displayName: 'MMSI', value: vesselDetails?.mmsi }, @@ -99,7 +123,9 @@ export default function VesselDetailsBox() { handleDurationChange(e.target.value)} > @@ -114,7 +140,7 @@ export default function VesselDetailsBox() {