Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 54x 54x 54x 54x 54x 26x 26x 15x 15x 15x 15x 15x 11x 10x 10x 2x 2x 2x 2x 2x 13x 15x 54x 54x 2x 2x | import { useEffect, useRef, useState } from "react";
import type { VehicleTripSnapshot } from "./vehicleTrip";
import { VehicleRequestError } from "./vehicles";
export type VehicleTripRequest = (
blockId: string, tripId: string, signal: AbortSignal
) => Promise<VehicleTripSnapshot>;
export function useVehicleTrip(
blockId: string,
tripId: string,
updatedAt: number | undefined,
enabled: boolean,
getVehicleTrip: VehicleTripRequest
) {
const [attempt, setAttempt] = useState(0);
const [state, setState] = useState<{
key?: string; data?: VehicleTripSnapshot; receivedAt?: number; loading: boolean; error?: string;
}>({ loading: true });
const key = `${blockId}:${tripId}`;
const failure = useRef({ key, count: 0, until: 0, permanent: false });
useEffect(() => {
if (failure.current.key !== key) failure.current = { key, count: 0, until: 0, permanent: false };
if (!enabled || document.hidden || !updatedAt || failure.current.permanent || failure.current.until > Date.now()) return;
const controller = new AbortController();
let timedOut = false;
const timeout = setTimeout(() => { timedOut = true; controller.abort(); }, 12000);
setState(previous => ({
...(previous.key === key ? previous : {}), key, loading: true, error: undefined,
}));
void getVehicleTrip(blockId, tripId, controller.signal).then(data => {
if (controller.signal.aborted) return;
failure.current = { key, count: 0, until: 0, permanent: false };
setState({ key, data, receivedAt: Date.now(), loading: false });
}).catch(error => {
Iif (controller.signal.aborted && !timedOut) return;
const count = failure.current.count + 1;
const retryAfter = error instanceof VehicleRequestError ? error.retryAfterMs : 0;
failure.current = {
key, count, until: Date.now() + Math.max(Math.min(15000 * 2 ** (count - 1), 120000), retryAfter),
permanent: error instanceof VehicleRequestError && error.permanent,
};
setState(previous => ({
...previous, key, loading: false,
error: timedOut ? "Trip progress timed out." : "Trip progress could not be updated.",
}));
}).finally(() => clearTimeout(timeout));
return () => { controller.abort(); clearTimeout(timeout); };
}, [key, blockId, tripId, updatedAt, enabled, attempt, getVehicleTrip]);
const current: typeof state = state.key === key ? state : { loading: true };
return {
...current,
retry() {
failure.current = { key, count: 0, until: 0, permanent: false };
setAttempt(value => value + 1);
},
};
}
|