api: reconfigered api handling

This commit is contained in:
Yordan Simeonov
2025-10-20 18:45:01 +02:00
parent d0194f0dc2
commit 98a2067b8d
9 changed files with 112 additions and 295 deletions

View File

@@ -1,7 +1,6 @@
import { getSeason, SeasonParticipant } from "@/apis/seasonApi";
import React, {
createContext,
ReactNode,
useCallback,
useContext,
useState,
@@ -13,17 +12,24 @@ type SeasonContextType = {
seasonNumber: number
) => Promise<SeasonParticipant[]>;
fetchSeasonCount: (showId: number) => Promise<number>;
fetchSeasonDates: (
showId: number,
seasonNumber: number
) => Promise<{ startDate?: string; endDate?: string | null } | null>;
};
const SeasonContext = createContext<SeasonContextType | null>(null);
export const SeasonProvider = ({ children }: { children: ReactNode }) => {
export const SeasonProvider = ({ children }: { children: React.ReactNode }) => {
const [seasonCache, setSeasonCache] = useState<
Record<string, SeasonParticipant[]>
>({});
const [seasonCountCache, setSeasonCountCache] = useState<
Record<number, number>
>({});
const [datesCache, setDatesCache] = useState<
Record<string, { startDate?: string; endDate?: string | null }>
>({});
const fetchSeasonParticipants = useCallback(
async (showId: number, seasonNumber: number) => {
@@ -61,15 +67,34 @@ export const SeasonProvider = ({ children }: { children: ReactNode }) => {
[seasonCountCache]
);
const fetchSeasonDates = useCallback(
async (showId: number, seasonNumber: number) => {
const key = `${showId}-${seasonNumber}`;
if (datesCache[key]) return datesCache[key];
try {
const season = await getSeason(showId, seasonNumber);
const dates = season
? { startDate: season.startDate, endDate: season.endDate }
: null;
if (dates) setDatesCache((c) => ({ ...c, [key]: dates }));
return dates;
} catch {
return null;
}
},
[datesCache]
);
return (
<SeasonContext.Provider
value={{ fetchSeasonParticipants, fetchSeasonCount }}
value={{ fetchSeasonParticipants, fetchSeasonCount, fetchSeasonDates }}
>
{children}
</SeasonContext.Provider>
);
};
export const useSeasonContext = () => {
const ctx = useContext(SeasonContext);
if (!ctx)