現在地表示をリアルタイム更新するように変更
This commit is contained in:
@@ -1,9 +1,13 @@
|
||||
import React, { createContext, useContext, useState } from "react";
|
||||
import React, { createContext, useContext, useState, useEffect } from "react";
|
||||
import { HeaderConfig } from "../lib/HeaderConfig";
|
||||
|
||||
import useInterval from "../lib/useInterval";
|
||||
const initialState = {
|
||||
currentTrain: [],
|
||||
setCurrentTrain: () => {},
|
||||
currentTrainLoading: "loading",
|
||||
setCurrentTrainLoading: () => {},
|
||||
getCurrentTrain: () => {},
|
||||
};
|
||||
|
||||
const CurrentTrainContext = createContext(initialState);
|
||||
@@ -15,7 +19,27 @@ export const useCurrentTrain = () => {
|
||||
export const CurrentTrainProvider = ({ children }) => {
|
||||
const [currentTrain, setCurrentTrain] = useState([]); //現在在線中の全列車 { num: 列車番号, delay: 遅延時分(状態), Pos: 位置情報 }
|
||||
const [currentTrainLoading, setCurrentTrainLoading] = useState("loading"); // success, error, loading
|
||||
const getCurrentTrain = () =>
|
||||
fetch(
|
||||
"https://script.google.com/macros/s/AKfycby9Y2-Bm75J_WkbZimi7iS8v5r9wMa9wtzpdwES9sOGF4i6HIYEJOM60W6gM1gXzt1o/exec",
|
||||
HeaderConfig
|
||||
)
|
||||
.then((response) => response.json())
|
||||
.then((d) =>
|
||||
d.map((x) => ({ num: x.TrainNum, delay: x.delay, Pos: x.Pos }))
|
||||
)
|
||||
.then((d) => {
|
||||
setCurrentTrain(d);
|
||||
setCurrentTrainLoading("success");
|
||||
})
|
||||
.catch(() => {
|
||||
console.log("えらー");
|
||||
setCurrentTrainLoading("error");
|
||||
});
|
||||
|
||||
useEffect(getCurrentTrain, []); //初回だけ現在の全在線列車取得
|
||||
|
||||
useInterval(getCurrentTrain, 15000); //15秒毎に全在線列車取得
|
||||
return (
|
||||
<CurrentTrainContext.Provider
|
||||
value={{
|
||||
@@ -23,6 +47,7 @@ export const CurrentTrainProvider = ({ children }) => {
|
||||
setCurrentTrain,
|
||||
currentTrainLoading,
|
||||
setCurrentTrainLoading,
|
||||
getCurrentTrain,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
|
Reference in New Issue
Block a user