I get data from Api but when I try to set the value with useState it give me an empty object

Francesco Coriolano

Hello everyone newbie here! I'm trying to use UseState hook to set setForecastData to the result that I receive from the API call, so then I will be able to access to it and use it elsewhere. After I set a new value to the hook I try to console.log it and it still give me an empty object! I don't know what Im doing wrong in here ? any suggestion is appreciate thanks! ( please see comments on code )

import axios from "axios";
import "./App.css";
import HomePage from "./Components/HomePage";
import MainPage from "./Components/MainPage";
const App = () => {
  const apiKey = process.env.REACT_APP_API_KEY;
  const [input, setInput] = useState("");
  const [city, setCity] = useState("");
  const [matchesArray, setMatchesArray] = useState([]);
  const [locationData, setLocationData] = useState();
  const [forecastData, setForecastData] = useState({});
  //get today weather info
  const getCurrentWeather = () => {
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&APPID=${apiKey}`
      )
      .then((res) => {
        console.log(res.data);
        let resp = res.data;
        setLocationData(resp);
      })
      .catch((err) => console.log(err));
  };

  //get weekly weather info
  const getWeeklyWeather = () => {
    let lat = matchesArray[0].lat;
    let lon = matchesArray[0].long;
    axios
      .get(
        `https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&exclude=minutely,current&units=metric&appid=${apiKey}`
      )
      .then((res) => {
        const utcOffset = res.data.timezone_offset;
        const hourly = res.data.hourly;
        const daily = res.data.daily;
        let hourlyReduced = hourly.map((hour, index) => ({
          id: index,
          temp: hour.temp,
          weatherCondition: hour.weather[0].main,
          weatherIcon: hour.weather[0].icon,
        }));
        hourlyReduced = hourlyReduced.slice(0, 24);
        const dailyReduced = daily.map((day, index) => ({
          id: index,
          minTemp: day.temp.min,
          maxTemp: day.temp.max,
          weatherCondition: day.weather[0].main,
          weatherIcon: day.weather[0].icon,
        }));

        const forecastInfo = {
          utcOffset: utcOffset,
          hourlyForecast: hourlyReduced,
          dailyForecast: dailyReduced,
        };
        setForecastData(forecastInfo); // NOT WORKING
        console.log(forecastData); // this is not working! it show me an empty object
        console.log(hourlyReduced); // this work fine and it show the result
        console.log(dailyReduced); // this work fine and it show the result
        
        return forecastInfo;
      });
  };
  

  return (
    <div className="App">
      <HomePage
        input={input}
        setInput={setInput}
        city={city}
        setCity={setCity}
        matchesArray={matchesArray}
        getCurrentWeather={getCurrentWeather}
        setMatchesArray={setMatchesArray}
        getWeeklyWeather={getWeeklyWeather}
        locationData={locationData}
        forecastData={forecastData}
      />
      <MainPage locationData={locationData} forecastData={forecastData} />
    </div>
  );
};

export default App;
wxker

useState hooks are asynchronous. Logging forecastData right after calling setForecastData will not guarantee that the hook has finished updating the state. Use a useEffect hook to log forecastData whenever it changes.

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

I try to get data from firebase and give me this error _CastError (Null check operator used on a null value)

ViewModel return clear object when i try to get data from it

React Hook useState doesnt work when I try passing in a JSON object fetched from an API request

Project freezes when I try to get data from api

When i try to get data from data for edit page it's showing me error

Why do I not need to set useState when a value is from props?

my req.body is empty when i try to get data from a form

When I try add insert a value into a asp.net Detailsview I get a "Object reference not set to an instance of an object"

when I try to insert value in list at the end it's give me None

I get 'undefined' when i try to fetch data from an API but when i access it again it works. why?

I get the 500 error when I try to return a value from PHP object/array. But it's ok return all the object

can I make Set/Map slap me when I try to use the wrong api on them?

Got undefined when I try to reach data from node API

Why i get this exception when i try to handle empty value on overflow menu?

Data from API call are stored in a Array but when i try to use that array in a function for further use it shows that array is empty . why?

404 ERROR when I try to GET data from google spreadsheet

NullPointerException when I try set TextView value

I get a duplicate empty file when I try to read the original

Why I get an empty file when I try to sort it?

when I Try to set Default value in Reactive Forms it Shows me NULL

When I try to delete an object from a list it never tells me it was found

why is it when I try to create a child class from a parent class(Downcasting), I get a null object

Why is this function return empty result when I try to get column name from a table in PostgreSQL?

Why are my cookies and signedCookies empty in req when I try to get them from port 3000?

I'm trying to make a simple app in flutter that fetches data from an API. However when I try running the code I get the following error

Why do I get an error (Notice: Undefined index) when I try to echo a value from my database?

Visual studio when i try to add reference get this : Instance object set as constant

I can print a state object array, but when I try to access a value from an object in the array, the whole object is undefined

Why I get exception when I try to fetch data from tables that has many to many relationship