Home > Mobile >  Undefined state using async await function with axios in React App
Undefined state using async await function with axios in React App

Time:11-16

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!

CodePudding user response:

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])
  • Related