Files
time_to_leave/apps/mobile/src/hooks/useWalkRoute.ts
T

62 lines
1.6 KiB
TypeScript

import { useState, useEffect } from 'react';
import type { WalkRoute } from '@timetoleave/core';
import { api } from '../services/api';
/**
* Fetch walk route between two points using the OSRM walking router.
* Skips the request if any coordinate is missing, resetting state to null.
* Mirrors the web app's useWalkRoute hook.
*/
export function useWalkRoute(
fromLat: number | undefined,
fromLng: number | undefined,
toLat: number | undefined,
toLng: number | undefined,
) {
const [walkRoute, setWalkRoute] = useState<WalkRoute | null>(null);
const [loading, setLoading] = useState<boolean>(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let isMounted = true;
const fetchRoute = async () => {
if (fromLat == null || fromLng == null || toLat == null || toLng == null) {
setWalkRoute(null);
setLoading(false);
setError(null);
return;
}
setLoading(true);
setError(null);
try {
const data = await api.getWalkRoute(fromLat, fromLng, toLat, toLng);
if (isMounted) {
setWalkRoute(data);
setLoading(false);
}
} catch (err: unknown) {
if (isMounted) {
const message = err instanceof Error ? err.message : 'Failed to fetch walk route';
setError(message);
}
} finally {
if (isMounted) {
setLoading(false);
}
}
};
fetchRoute();
return () => {
isMounted = false;
};
}, [fromLat, fromLng, toLat, toLng]);
return { walkRoute, loading, error };
}