81 lines
2.3 KiB
TypeScript
81 lines
2.3 KiB
TypeScript
import React, {
|
|
createContext,
|
|
useContext,
|
|
useState,
|
|
useEffect,
|
|
FC,
|
|
} from "react";
|
|
import { lineList, getStationList } from "../lib/getStationList";
|
|
|
|
type initialStateType = {
|
|
originalStationList: any[][];
|
|
setOriginalStationList: React.Dispatch<React.SetStateAction<any[]>>;
|
|
getStationDataFromName: (id: string) => any[];
|
|
getStationDataFromId: (id: string) => any[];
|
|
stationList: any[];
|
|
};
|
|
const initialState = {
|
|
originalStationList: [[]],
|
|
setOriginalStationList: () => {},
|
|
getStationDataFromName: () => [],
|
|
getStationDataFromId: () => [],
|
|
stationList: [],
|
|
};
|
|
|
|
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 getStationDataFromId: (id: string) => any[] = (id) => {
|
|
let returnArray = [];
|
|
Object.keys(originalStationList).forEach((key) => {
|
|
originalStationList[key].forEach((station) => {
|
|
if (station.StationNumber === id) {
|
|
returnArray = [...returnArray, ...getStationDataFromName(station.Station_JP)];
|
|
}
|
|
});
|
|
});
|
|
return returnArray;
|
|
};
|
|
const getStationDataFromName: (name: string) => any[] = (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;
|
|
};
|
|
const [stationList, setStationList] = useState<any[][]>([[]]);
|
|
useEffect(()=>{
|
|
if(originalStationList.length === 0) return;
|
|
const stationList =
|
|
lineList.map((d) =>
|
|
originalStationList[d].map((a) => ({
|
|
StationNumber: a.StationNumber,
|
|
StationName: a.Station_JP,
|
|
}))
|
|
);
|
|
setStationList(stationList);
|
|
},[originalStationList])
|
|
|
|
return (
|
|
<StationListContext.Provider
|
|
value={{ originalStationList, setOriginalStationList, getStationDataFromName, getStationDataFromId, stationList }}
|
|
>
|
|
{children}
|
|
</StationListContext.Provider>
|
|
);
|
|
};
|