Files
physical-expo/context/AppStateContext.tsx

103 lines
2.7 KiB
TypeScript

import { CardsSettings, OddsSettings, storage } from "@/lib/storage";
import React, {
createContext,
ReactNode,
useContext,
useEffect,
useState,
} from "react";
interface AppState {
selectedSportId: number | null;
selectedDate: Date;
selectedLeagueKey: string | null;
timezone: string;
oddsSettings: OddsSettings;
cardsSettings: CardsSettings;
}
interface AppStateContextType {
state: AppState;
updateSportId: (sportId: number | null) => void;
updateDate: (date: Date) => void;
updateLeagueKey: (leagueKey: string | null) => void;
updateTimezone: (timezone: string) => void;
updateOddsSettings: (settings: OddsSettings) => void;
updateCardsSettings: (settings: CardsSettings) => void;
}
const AppStateContext = createContext<AppStateContextType | undefined>(
undefined,
);
export function AppStateProvider({ children }: { children: ReactNode }) {
const [state, setState] = useState<AppState>({
selectedSportId: 1, // 默认足球
selectedDate: new Date(),
selectedLeagueKey: null,
timezone: "UTC",
oddsSettings: { enabled: false, selectedBookmakers: [] },
cardsSettings: { enabled: false },
});
useEffect(() => {
// Initial load of odds settings and cards settings
storage.getOddsSettings().then((settings) => {
setState((prev) => ({ ...prev, oddsSettings: settings }));
});
storage.getCardsSettings().then((settings) => {
setState((prev) => ({ ...prev, cardsSettings: settings }));
});
}, []);
const updateSportId = (sportId: number | null) => {
setState((prev) => ({ ...prev, selectedSportId: sportId }));
};
const updateDate = (date: Date) => {
setState((prev) => ({ ...prev, selectedDate: date }));
};
const updateLeagueKey = (leagueKey: string | null) => {
setState((prev) => ({ ...prev, selectedLeagueKey: leagueKey }));
};
const updateTimezone = (timezone: string) => {
setState((prev) => ({ ...prev, timezone }));
};
const updateOddsSettings = (settings: OddsSettings) => {
setState((prev) => ({ ...prev, oddsSettings: settings }));
storage.setOddsSettings(settings);
};
const updateCardsSettings = (settings: CardsSettings) => {
setState((prev) => ({ ...prev, cardsSettings: settings }));
storage.setCardsSettings(settings);
};
return (
<AppStateContext.Provider
value={{
state,
updateSportId,
updateDate,
updateLeagueKey,
updateTimezone,
updateOddsSettings,
updateCardsSettings,
}}
>
{children}
</AppStateContext.Provider>
);
}
export function useAppState() {
const context = useContext(AppStateContext);
if (!context) {
throw new Error("useAppState must be used within AppStateProvider");
}
return context;
}