skip to Main Content

After I fetched data from an api I am trying to update a state, but it is not updating.
I am also getting the response successfully.
I have also added the calling function.
Here is the function and state :


const getWeather = async (lat, lon) => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey.apiKey}`;
    const data = await fetch(url);
    const response = await data.json();
    console.log(response);
    console.log(response.main.temp);
    setWeather({
      lat: lat,
      lon: lon,
      temperature: Math.round(response.main.temp),
      feelstemp: Math.round(response.main.feels_like),
      desc: response.weather.description,
      humidity: response.main.humidity,
      pressure: response.main.pressure,
      visibility: response.visibilty,
      windspeed: response.wind.speed,
      sunrise: response.sys.sunrise,
      sunset: response.sys.sunset,
      city: response.city,
      country: response.sys.country,
      main: response.weather[0].main,
    });
    console.log(weather);
  };
//Calling function in another file.
useEffect(() => {
    if (navigator.geolocation) {
      getLocation()
        //If user allow location service then will fetch data & send it to get-weather function.
        .then((position) => {
          getWeather(position.coords.latitude, position.coords.longitude);
        })
        .catch((err) => {
          //If user denied location service then standard location weather will le shown on basis of latitude & latitude.
          getWeather(28.67, 77.22);
          alert(
            "You have disabled location service. Allow 'This APP' to access your location. Your current location will be used for calculating Real time weather."
          );
        });
    } else {
      alert("Geolocation not available");
    }
  }, []); 

Plese help me updating the state.

2

Answers


  1. Your response is successfully received through API means the code is working. But since in your code setWeather is a async function, it is not called synchronously in the component and the log is not updating correctly. To log the output, you need to use a useEffect hook like the following:

    useEffect(() => {
      console.log(weather);
    }, [weather]);
    

    This hook will detect the change in setWeather function whenever the weather state gets updated and trigger the log.

    To learn more about useEffect hook, see official documentation here: https://beta.reactjs.org/reference/react/useEffect

    Update: I just noticed there is a spelling error of the value visibility in your response.data JSON object. I recommend you should double-check the API reference to make sure it is correct.

    Login or Signup to reply.
  2. You still need to execute your function, you only defined the function getWeather but you still need to call it. You can not just go ahead and call getWeather later on in the code because of possible rerenders it will get fetched every time. You need to use useEffect for this.

      useEffect(() => {
        getWeather();
      }, []);
    

    But because you’re using getWeather in the useEffect you need to add it to the dependency array:

      useEffect(() => {
        getWeather();
      }, [getWeather]);
    

    But because getWeather is not a callback function you need to wrap getWeather with useCallback

    const getWeather = useCallback(async (lat, lon) => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey.apiKey}`;
        const data = await fetch(url);
        const response = await data.json();
        setWeather({
          lat: lat,
          lon: lon,
          temperature: Math.round(response.main.temp),
          feelstemp: Math.round(response.main.feels_like),
          desc: response.weather.description,
          humidity: response.main.humidity,
          pressure: response.main.pressure,
          visibility: response.visibilty,
          windspeed: response.wind.speed,
          sunrise: response.sys.sunrise,
          sunset: response.sys.sunset,
          city: response.city,
          country: response.sys.country,
          main: response.weather[0].main,
        });
      }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search