0

I am trying to fetch and display data from OpenWeather api but on first run the currentWeather object will be empty then on reload the data is fetched. Here is the code

import { Box, CssBaseline } from "@mui/material";
import { useEffect, useState } from "react";
import CardList from "./components/CardList";
import axios from 'axios'


function App() {
  const [currentWeather, setCurrentWeather] = useState({})

  useEffect(() => {
    const getCurrentWeather = (city) => {
      axios.get(`https://api.openweathermap.org/data/2.5/weather? q=${city}&appid=${API_KEY}&units=metric`)
      .then(res =>
        setCurrentWeather(res.data)
        )
      .catch(err =>
        console.log(err)
        )
      .finally(() => {
        console.log(currentWeather)
       }
       )
    }
    getCurrentWeather('Bulawayo')
}, [])



return (
  <Box sx={{
    p: 4,
    backgroundColor: "#f3f6fa",
  }}>
    <CssBaseline />
    <CardList currentWeather={currentWeather} />
  </Box>
);
}

export default App;

any help would be appreciated thank u

Dave
  • 5
  • 1
  • 2
  • Can you clarify what you mean by "on reload"? Do you mean that you have to manually reload the page? Or are you just referring to the component re-rendering? – David Apr 08 '22 at 13:11
  • if i edit the component and save it works so i'm guessing it would have reloaded – Dave Apr 08 '22 at 13:13
  • 1
    *"edit the component and save"* - So by "reload" you mean make changes to the code and re-publish entirely? It's sitll not clear to me specifically what you're referring to. In the absense of any specific error messages, I would expect the component shown to perform two renders. The first render would be using the empty object, then when the AJAX operation completes and the state is updated there would be a re-render with the new state. Is that not what's happening here? – David Apr 08 '22 at 13:15
  • like after i run npm start the currentWeather state will be empty as you've seen that i console.log it , but then if i edit anything, i'm guessing that way it won't re-render the cached code , the currentWeather state is changed to the value of data fetched so i'm not sure what to do. Thank you – Dave Apr 08 '22 at 13:21
  • 1
    Oh, so you're specifically referring to the `console.log` statement in the `finally` block? In that case this is essentially just a duplicate of [The useState set method is not reflecting a change immediately](https://stackoverflow.com/q/54069253/328193) (I've already voted to close the question as needing debugging details, but another user can vote to close as a duplicate.) State updates are asynchronous. The code is working, you just have an incorrect expectation where you try to log a value to the console. – David Apr 08 '22 at 13:23
  • thank you so much it is now ok. The mistake was as you stated!! – Dave Apr 08 '22 at 13:49

0 Answers0