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 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | 152x 243x 152x 152x 152x 50x 37x 37x 13x 13x 13x 23x 2x 2x 21x 11x 11x 11x 8x 7x 3x 3x 11x 152x 152x | import { useEffect, useState } from "react";
import {
getWalkingEstimates,
WalkingEstimate,
WalkingStop,
} from "./walking";
export type WalkingEstimateInput = Pick<WalkingStop, "lat" | "lng"> & { locid?: number };
export type WalkingEstimateRequest = typeof getWalkingEstimates;
interface State {
key: string;
status: "off" | "loading" | "ready" | "error";
estimates: Map<number, WalkingEstimate>;
error?: string;
}
export function useWalkingEstimates(
origin: number[],
stops: WalkingEstimateInput[],
enabled: boolean,
requestEstimates: WalkingEstimateRequest = getWalkingEstimates
) {
const key = JSON.stringify({
origin: origin?.slice(0, 2),
stops: stops.map(({ lat, lng, locid }) => ({ lat, lng, locid })),
});
const [state, setState] = useState<State>({
estimates: new Map(),
key,
status: "off",
});
const [retry, setRetry] = useState(0);
useEffect(() => {
if (!enabled) {
setState({ estimates: new Map(), key, status: "off" });
return;
}
const input: {
origin: number[];
stops: WalkingEstimateInput[];
} = JSON.parse(key);
const validStops: WalkingStop[] = [];
for (const stop of input.stops) {
if (typeof stop.locid !== "number" || !Number.isSafeInteger(stop.locid) || stop.locid <= 0) {
setState({
error: "Walking estimates require valid current-location and stop coordinates.",
estimates: new Map(),
key,
status: "error"
});
return;
}
validStops.push({ lat: stop.lat, lng: stop.lng, locid: stop.locid });
}
const request = new AbortController();
setState({ estimates: new Map(), key, status: "loading" });
requestEstimates(input.origin, validStops, request.signal)
.then((estimates) => {
if (!request.signal.aborted)
setState({ estimates, key, status: "ready" });
})
.catch((error) => {
Eif (!request.signal.aborted)
setState({
error:
error instanceof Error
? error.message
: "Could not load walking estimates.",
estimates: new Map(),
key,
status: "error",
});
});
return () => request.abort();
}, [enabled, key, retry, requestEstimates]);
const current: State =
enabled && state.key === key
? state
: {
estimates: new Map<number, WalkingEstimate>(),
key,
status: enabled ? "loading" : "off",
};
return { ...current, refresh: () => setRetry((value) => value + 1) };
}
|