aboutsummaryrefslogtreecommitdiff
path: root/src/pages/Home.tsx
blob: f92847adac4988b520ac7bba039101b324a05c37 (plain)
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
import { useNavigate } from "react-router-dom";
import useSWR from "swr";

interface Stop {
	stopId: number
	name: string;
	latitude?: number;
	longitude?: number;
	lines: string[];
}

interface CachedStopList {
	timestamp: number;
	data: Stop[];
}

export function Home() {
	const navigate = useNavigate()
	const { data, error, isLoading } = useSWR<Stop[]>('home', async () => {
		const rawCachedData = localStorage.getItem('cachedStopList');
		if (rawCachedData) {
			const parsedData: CachedStopList = JSON.parse(rawCachedData)

			// Cache for 12 hours
			if (Date.now() - parsedData.timestamp < 1000 * 60 * 60 * 12) {
				return parsedData.data
			} else {
				localStorage.removeItem('cachedStopList')
			}
		}

		const response = await fetch('/api/ListStops')
		const body = await response.json();

		const cachedData: CachedStopList = {
			timestamp: Date.now(),
			data: body
		}

		localStorage.setItem('cachedStopList', JSON.stringify(cachedData));
		
		return body;
	});

	const handleStopSearch = async (event: React.FormEvent) => {
		event.preventDefault()

		const stopId = (event.target as HTMLFormElement).stopId.value
		const searchNumber = parseInt(stopId)
		if (data?.find(stop => stop.stopId === searchNumber)) {
			navigate(`/${searchNumber}`)
		} else {
			alert("Parada no encontrada")
		}
	}

	if (isLoading) return <h1>Loading...</h1>
	if (error) return <h1>Error</h1>

	return (
		<>
			<h1>Home</h1>

			<form action="none" onSubmit={handleStopSearch}>
				<div>
					<label htmlFor="stopId">
						ID
					</label>
					<input type="number" placeholder="ID de parada" id="stopId" />
				</div>

				<button type="submit">Buscar</button>
			</form>

			<ul>
				{data?.sort((a, b) => a.stopId - b.stopId).map((stop: Stop) => (
					<li key={stop.stopId}>
						<a href={`/${stop.stopId}`}>
							({stop.stopId}) {stop.name} - {stop.lines?.join(', ')}
						</a>
					</li>
				))}
			</ul>
		</>
	)
}