54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
import React, {
|
|
createContext,
|
|
useContext,
|
|
useState,
|
|
useEffect,
|
|
FC,
|
|
} from "react";
|
|
import { getStationList } from "../lib/getStationList";
|
|
|
|
type initialStateType = {
|
|
originalStationList: any[];
|
|
setOriginalStationList: React.Dispatch<React.SetStateAction<any[]>>;
|
|
getStationData: (id: string) => void;
|
|
};
|
|
const initialState = {
|
|
originalStationList: [],
|
|
setOriginalStationList: () => {},
|
|
getStationData: () => {},
|
|
};
|
|
|
|
const StationListContext = createContext<initialStateType>(initialState);
|
|
type Props = {
|
|
children: React.ReactNode;
|
|
};
|
|
export const useStationList = () => {
|
|
return useContext(StationListContext);
|
|
};
|
|
|
|
export const StationListProvider: FC<Props> = ({ children }) => {
|
|
const [originalStationList, setOriginalStationList] = useState<any[]>([]);
|
|
useEffect(() => {
|
|
getStationList().then(setOriginalStationList);
|
|
}, []);
|
|
const getStationData: (name: string) => void = (name) => {
|
|
const returnArray = [];
|
|
Object.keys(originalStationList).forEach((key) => {
|
|
originalStationList[key].forEach((station) => {
|
|
if (station.Station_JP === name) {
|
|
if (!!station.jslodApi) returnArray.push(station);
|
|
}
|
|
});
|
|
});
|
|
return returnArray;
|
|
};
|
|
|
|
return (
|
|
<StationListContext.Provider
|
|
value={{ originalStationList, setOriginalStationList, getStationData }}
|
|
>
|
|
{children}
|
|
</StationListContext.Provider>
|
|
);
|
|
};
|