From 1eb26151dd2c5a4d80b5591113e7ef532cab78f8 Mon Sep 17 00:00:00 2001 From: Romulus21 Date: Sun, 24 Sep 2023 19:14:29 +0200 Subject: [PATCH] add timer to fetch --- resources/js/pages/Weather.tsx | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) 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) } }