开发者

I want to fetch data from a weather API based on the users current location. This will only work part of the time. What am I missing?

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

I want to fetch data from a weather API based on the users current location. This will only work part of the time. What am I missing?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜