aboutsummaryrefslogtreecommitdiffhomepage
path: root/frontend/app/routes/golf.$gameId.watch.tsx
blob: 556eb03298c5c8d1f46b7a8f8370f71fb339772a (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
import { Provider as JotaiProvider, createStore } from "jotai";
import { useMemo } from "react";
import type { LoaderFunctionArgs, MetaFunction } from "react-router";
import { redirect, useLoaderData } from "react-router";
import { ensureUserLoggedIn } from "../.server/auth";
import { ApiClientContext, createApiClient } from "../api/client";
import GolfWatchApp from "../components/GolfWatchApp";

export const meta: MetaFunction<typeof loader> = ({ data }) => [
	{
		title: data
			? `Golf Watching ${data.game.display_name} | PHPerKaigi 2025 Albatross`
			: "Golf Watching | PHPerKaigi 2025 Albatross",
	},
];

export async function loader({ params, request }: LoaderFunctionArgs) {
	const { token } = await ensureUserLoggedIn(request);
	const apiClient = createApiClient(token);

	const gameId = Number(params.gameId);

	try {
		const [{ game }, { ranking }, { states: gameStates }] = await Promise.all([
			await apiClient.getGame(gameId),
			await apiClient.getGameWatchRanking(gameId),
			await apiClient.getGameWatchLatestStates(gameId),
		]);

		return {
			apiToken: token,
			game,
			ranking,
			gameStates,
		};
	} catch {
		throw redirect("/dashboard");
	}
}

export default function GolfWatch() {
	const { apiToken, game, ranking, gameStates } =
		useLoaderData<typeof loader>();

	const store = useMemo(() => {
		void game.game_id;
		return createStore();
	}, [game.game_id]);

	return (
		<JotaiProvider store={store}>
			<ApiClientContext.Provider value={createApiClient(apiToken)}>
				<GolfWatchApp
					key={game.game_id}
					game={game}
					initialGameStates={gameStates}
					initialRanking={ranking}
				/>
			</ApiClientContext.Provider>
		</JotaiProvider>
	);
}