-1

I am creating a basic weather app that fetches data from the Openweathermap API and displays it on the page.

I don't get why the console.log(data) is showing undefined in my console?

   const [data, setData] = useState()

   useEffect(() => {

      const fetchData = async () => {
         const res = await axios.get(url)
         setData(res.data)
         console.log(data)
      }

      fetchData()
   }, [])

Should the console.log(data) only run once the await part of the function is resolved?

The data does get retrieved successfully and displays on the page correctly, as I am only rendering the html if data is defined:

return (
         {data && (
            <div className="weather">
                //content goes here
            <div/>

I just don't understand why it is showing as undefined in the console?

Thanks in advance!

Phil
  • 157,677
  • 23
  • 242
  • 245
newportkat
  • 19
  • 4
  • 1
    Why are you logging your API data at all? It sounds like your component renders correctly so what were you trying to debug? – Phil Nov 16 '22 at 05:29
  • I wanted to see the json data that was returned for other reasons. This caught my attention and was curious. The answer from Sachila cleared it up for me! – newportkat Nov 16 '22 at 05:44
  • Use your browser's _Network_ dev tools panel to debug requests and responses. – Phil Nov 16 '22 at 05:45

1 Answers1

1

setData is asynchronous. it won't update the data immediately hence you don't see the result immediately.

you can use useEffect to detect the changes once state is updated

useEffect(() => {console.log(data)}, [data])
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80