diff --git a/resources/js/pages/Weather.tsx b/resources/js/pages/Weather.tsx index 9736ac0..855aa1d 100644 --- a/resources/js/pages/Weather.tsx +++ b/resources/js/pages/Weather.tsx @@ -7,15 +7,25 @@ import Card from "../components/Card" const Weather = () => { const [currentWeather, setCurrentWeather] = useState(null) + const [fetchTime, setFetchTime] = useState(0) + const [count, setCount] = useState(0) const [weatherDays, setWeatherDays] = useState<[string, WeatherValue[]][]|null>(null) - const {errorLabel, errorCatch, cleanErrors, axiosGet} = useAxiosTools() + const {loading, setLoading, errorLabel, errorCatch, cleanErrors, axiosGet} = useAxiosTools() useEffect(() => { - (async () => fetchWeather())() - }, []) + const timer = setInterval(() => { + if (!loading && (fetchTime + 5 * 60) < getCurrentTime()) { + fetchWeather() + } + }, 1000) + return () => clearInterval(timer) + }, [fetchTime]) + + const getCurrentTime = () => Number(((new Date).getTime() /1000).toFixed()) const fetchWeather = async () => { try { + setLoading(true) cleanErrors() const res = await axiosGet(`/api/weather`) const currentWeather = res.data.list[0] @@ -46,8 +56,11 @@ const Weather = () => { }) setWeatherDays(weatherDays) setCurrentWeather(currentWeather) + setFetchTime(getCurrentTime()) } catch (e) { errorCatch(e) + } finally { + setLoading(false) } }