:api added seasonApi to fetch seasons for a show

This commit is contained in:
Cron1cle
2025-10-07 16:14:11 +02:00
parent 9da89e6b90
commit de2778d6db
11 changed files with 462 additions and 156 deletions

View File

@@ -0,0 +1,74 @@
import { getSeason, SeasonParticipant } from "@/apis/seasonApi";
import React, { createContext, useContext, useState, useCallback } from "react";
type SeasonContextType = {
fetchSeasonParticipants: (
showId: number,
seasonNumber: number
) => Promise<SeasonParticipant[]>;
fetchSeasonCount: (showId: number) => Promise<number>;
};
const SeasonContext = createContext<SeasonContextType | null>(null);
export const SeasonProvider = ({ children }: { children: React.ReactNode }) => {
const [seasonCache, setSeasonCache] = useState<
Record<string, SeasonParticipant[]>
>({});
const [seasonCountCache, setSeasonCountCache] = useState<
Record<number, number>
>({});
const fetchSeasonParticipants = useCallback(
async (showId: number, seasonNumber: number) => {
const key = `${showId}-${seasonNumber}`;
if (seasonCache[key]) return seasonCache[key];
try {
const season = await getSeason(showId, seasonNumber);
const participants = season?.participants ?? [];
setSeasonCache((c) => ({ ...c, [key]: participants }));
return participants;
} catch {
return [];
}
},
[seasonCache]
);
const fetchSeasonCount = useCallback(
async (showId: number) => {
if (seasonCountCache[showId] !== undefined)
return seasonCountCache[showId];
let n = 0;
for (let s = 1; s <= 50; s++) {
try {
const season = await getSeason(showId, s);
if (!season) break;
n = s;
} catch {
break;
}
}
setSeasonCountCache((c) => ({ ...c, [showId]: n }));
return n;
},
[seasonCountCache]
);
return (
<SeasonContext.Provider
value={{ fetchSeasonParticipants, fetchSeasonCount }}
>
{children}
</SeasonContext.Provider>
);
};
export const useSeasonContext = () => {
const context = useContext(SeasonContext);
if (!context)
throw new Error("useSeasonContext must be used within a SeasonProvider");
return context;
};