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: () => {}, allCustomTrainData: [], }; const AllTrainDiagramContext = createContext(initialState); export const useAllTrainDiagram = () => useContext(AllTrainDiagramContext); export const AllTrainDiagramProvider = ({ children }) => { const [allTrainDiagram, setAllTrainDiagram] = useState(trainList); const [allCustomTrainData, setAllCustomTrainData] = 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) => { setAllCustomTrainData(res[0].data); }) .catch(() => { alert("カスタム列車データの取得に失敗しました。"); }); }; useEffect(() => { // カスタム列車データの取得 getCustomTrainData(); }, []); useInterval(getCustomTrainData, 30000); // 30秒毎にカスタム列車データ取得 return ( {children} ); };