add timer to fetch
This commit is contained in:
@@ -7,15 +7,25 @@ import Card from "../components/Card"
|
|||||||
const Weather = () => {
|
const Weather = () => {
|
||||||
|
|
||||||
const [currentWeather, setCurrentWeather] = useState<WeatherValue|null>(null)
|
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 [weatherDays, setWeatherDays] = useState<[string, WeatherValue[]][]|null>(null)
|
||||||
const {errorLabel, errorCatch, cleanErrors, axiosGet} = useAxiosTools()
|
const {loading, setLoading, errorLabel, errorCatch, cleanErrors, axiosGet} = useAxiosTools()
|
||||||
|
|
||||||
useEffect(() => {
|
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 () => {
|
const fetchWeather = async () => {
|
||||||
try {
|
try {
|
||||||
|
setLoading(true)
|
||||||
cleanErrors()
|
cleanErrors()
|
||||||
const res = await axiosGet(`/api/weather`)
|
const res = await axiosGet(`/api/weather`)
|
||||||
const currentWeather = res.data.list[0]
|
const currentWeather = res.data.list[0]
|
||||||
@@ -46,8 +56,11 @@ const Weather = () => {
|
|||||||
})
|
})
|
||||||
setWeatherDays(weatherDays)
|
setWeatherDays(weatherDays)
|
||||||
setCurrentWeather(currentWeather)
|
setCurrentWeather(currentWeather)
|
||||||
|
setFetchTime(getCurrentTime())
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
errorCatch(e)
|
errorCatch(e)
|
||||||
|
} finally {
|
||||||
|
setLoading(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user