add timer to fetch

This commit is contained in:
Romulus21
2023-09-24 19:14:29 +02:00
parent 32ddcc78ce
commit 1eb26151dd

View File

@@ -7,15 +7,25 @@ import Card from "../components/Card"
const Weather = () => {
const [currentWeather, setCurrentWeather] = useState<WeatherValue|null>(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)
}
}