import trainList from "@/assets/originData/trainList"; 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( () => allTrainDiagram && setKeyList(Object.keys(allTrainDiagram)), [allTrainDiagram] ); useEffect(() => { 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(() => { // カスタム列車データの取得 fetch("https://n8n.haruk.in/webhook/jr-shikoku-position-custom-datalist") .then((res) => res.json()) .then((res) => { setAllCustonTrainData(res[0].data); }) .catch(() => { alert("カスタム列車データの取得に失敗しました。"); }); }, []); return ( {children} ); };