How can I make a global variable in axios?

Viewed 4879

So, I am just learning about axios and everything looks right, but I suppose I'm not understanding something about global scopes. Here is my code:

axios.get('https://api.github.com/users/social-collab')
.then(function (response) {
console.log('Response: ', response.data);
const data = response.data;
return data;
})
.catch(function (handleError) {
console.log('Error: ', handleError);
},[]);

const myData = function(data) {

name = data.name; // This is the line with the error: data is not defined. But it is, isn't it?
return name;
}

console.log(myData(data));
2 Answers

You don't need a global scope, just chain another .then with your function myData.

const myData = function(data) {
  name = data.name;
  console.log('name:', name)
  return name;
}

axios.get('https://api.github.com/users/social-collab')
.then(response => {
  const data = response.data;
  return data
})
.then(myData)
.catch(err => {
  console.log('Error: ', err);
})
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

The way to get data out of Promises is by supplying a function to .then.

If you return something from an async function (promise which will get your data from somewhere else) then you won't get the return value immediately. You can check my solution to understand better.

function getData() {
  axios
    .get("https://api.github.com/users/social-collab")
    .then(function (response) {
      console.log("Response: ", response.data);
      return response.data;
    })
    .catch(function (handleError) {
      console.log("Error: ", handleError);
    }, []);
}

const myData = function (data) {
  name = data.name;
  console.log(name);
};

getData().then((data) => {
  myData(data);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script>

Related