Home > Blockchain >  I want to fetch data from a weather API based on the users current location. This will only work par
I want to fetch data from a weather API based on the users current location. This will only work par

Time:12-07

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, setUrl] = 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;

CodePudding user response:

Include separate useEffect with url as a side effect to fire the API call

useEffect(() =>{
      getLocation();  

},[])

useEffect(() =>{    
    if(url){ 
      getWeater();
    }    
},[url])

CodePudding user response:

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 calling api after ten sec

  • Related