I know that [] in useEffect will cause the functions to run one time. Everything else I try creates an infinite loop. The get request works once but will not work again after I refresh the page. Any help would be appreciated. Thanks!
import React from 'react';
import { useState, useEffect } from 'react';
import axios from 'axios';
const Weather = () =>{
const [weather, setWeather] = useState();
const [lat, setLat] = useState([]);
const [long, setLong] = useState([]);
const [url, set开发者_如何学CUrl] = useState(``);
const getLocation = () => {
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition((position) =>{
let la = position.coords.latitude;
let lon = position.coords.longitude;
setLat(la)
setLong(lon)
setUrl(`http://api.weatherapi.com/v1/current.json?key=6e6263afb84f44279f731543222510&q=${lat},${long}`)
})
}
}
const getWeater = async () =>{
await axios.get(url).then((response) =>{
const weatherData = response.data;
setWeather(weatherData);
console.log(weather)
})
}
useEffect(() =>{
getLocation();
getWeater();
},[])
}
export default Weather;
Include separate useEffect with url
as a side effect to fire the API call
useEffect(() =>{
getLocation();
},[])
useEffect(() =>{
if(url){
getWeater();
}
},[url])
setInterval we can use to call these functions after some seconds or minutes , Inside the setInterval just call a function to call these two functions , I have attached a example of code
精彩评论