Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Undefined state using async await function with axios in React App

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading