some guy
some guy

Reputation: 45

Axios prints value on console but returns undefined

I have quite an issue for some time and is getting on my nerves and it doesn't make sense. I have used axios on my react frontend and it works perfect when assigning the get value to the state. But when using it in a normal javascript code, I appear to have this following issue: i can print the object's value in the console but it will return only undefined.. Here is my code:

login = () => {
        let data;
        axios.get('https://myaddress/authenticate')
            .then(response => {
                data = response;
                console.log('data here', data);
            })
            .catch(error => {
                console.error('auth.error', error);
            });
        console.log('eee', data);
        return data;
    };

Here we are talking about axios strictly.

Upvotes: 0

Views: 3291

Answers (2)

darklightcode
darklightcode

Reputation: 2772

You can't return an ajax response because it's asynchronous. You should wrap your function into a promise or pass a callback to login

UPDATE: As @Thilo said in the comments, async/await would be another option, but it will let you set the response to data tho ...

1. Wrap into a promise

 login = () => new Promise((resolve, reject)=>{
      axios.get('https://myaddress/authenticate')
      .then(response => {
           resolve(response)
      })
      .catch(error => {
           reject(error)
      });
 });

 // Usage example
 login()
    .then(response =>{
       console.log(response) 
    })
    .catch(error => {
       console.log(error)
    })

2. Pass a callback

login = (callback) => {

   axios.get('https://myaddress/authenticate')
        .then(response => {
            callback(null,response)
        })
        .catch(error => {
            callback(error,null)
        });
};

// Usage example
login((err, response)=>{

     if( err ){
       throw err;
     }

     console.log(response);

})

3. Async/Await

login = async () => {

  // You can use 'await' only in a function marked with 'async'

  // You can set the response as value to 'data' by waiting for the promise to get resolved
  let data = await axios.get('https://myaddress/authenticate');

  // now you can use a "synchronous" data, only in the 'login' function ...
  console.log('eee', data);

  return data; // don't let this trick you, it's not the data value, it's a promise

};

// Outside usage
console.log( login() ); // this is pending promise

Upvotes: 5

squeekyDave
squeekyDave

Reputation: 962

In ES7/ES8 you can do async/await like a boss:

login = () => {
  return new Promise((resolve, reject) => {
      axios.get('https://myaddress/authenticate')
        .then(response => {
            resolve(response)
          })
          .catch(error => {
              console.error('auth.error', error);
              reject(error)
          });
  });     
};

  async function getData() {
    try{
      const data = await login()
    } catch(error){
      // handle error
    }
    return data;
  }
  getData()
  .then((data) => console.log(data));

Upvotes: 0

Related Questions