83 lines
2.5 KiB
JavaScript
83 lines
2.5 KiB
JavaScript
import trainList from "@/assets/originData/trainList";
|
|
import useInterval from "@/lib/useInterval";
|
|
import { AS } from "@/storageControl";
|
|
import React, { createContext, useContext, useEffect, useState } from "react";
|
|
const initialState = {
|
|
allTrainDiagram: undefined,
|
|
setAllTrainDiagram: () => {},
|
|
allCustonTrainData: [],
|
|
};
|
|
|
|
const AllTrainDiagramContext = createContext(initialState);
|
|
|
|
export const useAllTrainDiagram = () => useContext(AllTrainDiagramContext);
|
|
|
|
export const AllTrainDiagramProvider = ({ children }) => {
|
|
const [allTrainDiagram, setAllTrainDiagram] = useState(trainList);
|
|
const [allCustonTrainData, setAllCustonTrainData] = useState([]); // カスタム列車データ
|
|
const [keyList, setKeyList] = useState(); // 第二要素
|
|
useEffect(() => {
|
|
if (allTrainDiagram && Object.keys(allTrainDiagram).length > 0)
|
|
setKeyList(Object.keys(allTrainDiagram));
|
|
else setKeyList([]);
|
|
}, [allTrainDiagram]);
|
|
const getTrainDiagram = () =>
|
|
fetch("https://n8n.haruk.in/webhook/JR-shikoku-diagram-migrate-original")
|
|
.then((res) => res.json())
|
|
.then((res) => res.data)
|
|
.then((res) => {
|
|
const data = {};
|
|
res.forEach((d) => {
|
|
const keys = Object.keys(d);
|
|
data[keys] = d[keys];
|
|
});
|
|
return data;
|
|
})
|
|
.then((res) => {
|
|
setAllTrainDiagram(res);
|
|
AS.setItem("allTrainDiagram", JSON.stringify(res));
|
|
})
|
|
.catch((d) => {
|
|
AS.getItem("allTrainDiagram")
|
|
.then((d) => setAllTrainDiagram(JSON.parse(d)))
|
|
.catch(() => {
|
|
alert("初回の路線情報の取得に失敗しました。");
|
|
});
|
|
});
|
|
|
|
useEffect(() => {
|
|
getTrainDiagram();
|
|
}, []);
|
|
useInterval(getTrainDiagram, 30000); //30秒毎に全在線列車取得
|
|
|
|
const getCustomTrainData = () => {
|
|
fetch("https://n8n.haruk.in/webhook/jr-shikoku-position-custom-datalist")
|
|
.then((res) => res.json())
|
|
.then((res) => {
|
|
setAllCustonTrainData(res[0].data);
|
|
})
|
|
.catch(() => {
|
|
alert("カスタム列車データの取得に失敗しました。");
|
|
});
|
|
};
|
|
|
|
useEffect(() => {
|
|
// カスタム列車データの取得
|
|
getCustomTrainData();
|
|
}, []);
|
|
useInterval(getCustomTrainData, 30000); // 30秒毎にカスタム列車データ取得
|
|
|
|
return (
|
|
<AllTrainDiagramContext.Provider
|
|
value={{
|
|
allTrainDiagram,
|
|
setAllTrainDiagram,
|
|
allCustonTrainData,
|
|
keyList,
|
|
}}
|
|
>
|
|
{children}
|
|
</AllTrainDiagramContext.Provider>
|
|
);
|
|
};
|