DEV Community

HAFIZ ABDULMANAN
HAFIZ ABDULMANAN

Posted on

?Assigning Api resposne to a variable undefined error

I am getting undefined for variable d; even console.log(res.data.results[0]) is working fine

import './App.css';
import a from 'axios'


function App() {
  let d;
  a.get("https://randomuser.me/api/")
  .then(res => {
    //console.log(res.data.results[0])
    d = res.data.results[0]
  })
  .catch(err => console.log("Its en error"))

  console.log(d) // undefined

  return (
    <div className="App">

    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
hamsof profile image
HAFIZ ABDULMANAN

Today after two years when I see this post I realize that the answer is really simple I have to use callbacks or return from with in then block thats how async programming works

I was dumb at that time!

Collapse
 
hamsof profile image
HAFIZ ABDULMANAN

I thing the issue is with Async programming but i am not getting the actual simple reason