mobile app phase 1
This commit is contained in:
@@ -1,80 +1 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import type { Journey } from "@/types";
|
||||
import { parseHafasJourneys } from "@/lib/hafas-client";
|
||||
import { hafasDateTime } from "@/lib/hafas-time";
|
||||
|
||||
export function useJourneys(
|
||||
fromStationExtId: string | null,
|
||||
toStationExtId: string | null,
|
||||
date: Date,
|
||||
refreshKey = 0,
|
||||
) {
|
||||
const [journeys, setJourneys] = useState<Journey[]>([]);
|
||||
const [loading, setLoading] = useState<boolean>(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
||||
const fetchJourneys = async () => {
|
||||
if (!fromStationExtId || !toStationExtId || !date) {
|
||||
return;
|
||||
}
|
||||
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const { date: hafasDate, time: hafasTime } = hafasDateTime(date);
|
||||
|
||||
const body = {
|
||||
svcReqL: [
|
||||
{
|
||||
meth: "TripSearch",
|
||||
req: {
|
||||
depLocL: [{ type: "S", extId: fromStationExtId }],
|
||||
arrLocL: [{ type: "S", extId: toStationExtId }],
|
||||
outDate: hafasDate,
|
||||
outTime: hafasTime,
|
||||
numF: 5,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const response = await fetch("/api/hafas", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errBody = await response.json().catch(() => ({}));
|
||||
throw new Error(errBody.error ?? `HAFAS request failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
const result = parseHafasJourneys(data, hafasDate, date);
|
||||
|
||||
if (isMounted) {
|
||||
setJourneys(result);
|
||||
setLoading(false);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (isMounted) {
|
||||
const message = err instanceof Error ? err.message : "Failed to fetch journeys";
|
||||
setError(message);
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
fetchJourneys();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [fromStationExtId, toStationExtId, date, refreshKey]);
|
||||
|
||||
return { journeys, loading, error };
|
||||
}
|
||||
../lib/hafas-client../lib/hafas-time
|
||||
|
||||
Reference in New Issue
Block a user