Search code examples
javascriptfunctionvariablesaxiosglobal-variables

How can I make a global variable in axios?


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));

Solution

  • 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.