2022-09-03 06:51:57 +00:00
|
|
|
import React, { createContext, useCallback } from "react";
|
|
|
|
import useSWRImmutable from "swr/immutable";
|
|
|
|
|
|
|
|
import { jsonFetcher } from "../lib/api";
|
2022-09-06 19:15:27 +00:00
|
|
|
import type { GameName } from "../lib/games";
|
2022-09-03 06:51:57 +00:00
|
|
|
|
|
|
|
interface Game {
|
|
|
|
id: number;
|
|
|
|
name: GameName;
|
|
|
|
nexus_game_id: number;
|
|
|
|
}
|
|
|
|
interface GamesContext {
|
|
|
|
games?: Game[] | null;
|
|
|
|
getGameNameById: (id: number) => GameName | undefined;
|
|
|
|
error?: any;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const GamesContext = createContext<GamesContext>({
|
|
|
|
games: null,
|
|
|
|
getGameNameById: () => undefined,
|
|
|
|
});
|
|
|
|
|
|
|
|
const GamesProvider: React.FC = ({ children }) => {
|
|
|
|
const { data, error } = useSWRImmutable(
|
|
|
|
"https://mods.modmapper.com/games.json",
|
|
|
|
(_) => jsonFetcher<Game[]>(_, { notFoundOk: false })
|
|
|
|
);
|
|
|
|
|
|
|
|
const getGameNameById = useCallback(
|
|
|
|
(id: number): GameName | undefined => {
|
|
|
|
if (data) {
|
2022-09-05 22:02:48 +00:00
|
|
|
return data.find((game) => game.id === id)?.name;
|
2022-09-03 06:51:57 +00:00
|
|
|
}
|
|
|
|
},
|
|
|
|
[data]
|
|
|
|
);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<GamesContext.Provider
|
|
|
|
value={{
|
|
|
|
games: data,
|
|
|
|
getGameNameById,
|
|
|
|
error,
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</GamesContext.Provider>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default GamesProvider;
|