Axios prints value on console but returns undefined












0















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.










share|improve this question




















  • 2





    Possible duplicate of How do I return the response from an asynchronous call?

    – Robin Zigmond
    Nov 21 '18 at 13:40











  • @RobinZigmond it is not, here we are talking about axios strictly

    – some guy
    Nov 21 '18 at 13:44






  • 1





    the specifics of the library don't matter, it's still asychronous, so the same issues and same possible solutions are all relevant.

    – Robin Zigmond
    Nov 21 '18 at 13:47
















0















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.










share|improve this question




















  • 2





    Possible duplicate of How do I return the response from an asynchronous call?

    – Robin Zigmond
    Nov 21 '18 at 13:40











  • @RobinZigmond it is not, here we are talking about axios strictly

    – some guy
    Nov 21 '18 at 13:44






  • 1





    the specifics of the library don't matter, it's still asychronous, so the same issues and same possible solutions are all relevant.

    – Robin Zigmond
    Nov 21 '18 at 13:47














0












0








0








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.










share|improve this question
















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.






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





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






javascript axios






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 13:46







some guy

















asked Nov 21 '18 at 13:39









some guysome guy

176




176








  • 2





    Possible duplicate of How do I return the response from an asynchronous call?

    – Robin Zigmond
    Nov 21 '18 at 13:40











  • @RobinZigmond it is not, here we are talking about axios strictly

    – some guy
    Nov 21 '18 at 13:44






  • 1





    the specifics of the library don't matter, it's still asychronous, so the same issues and same possible solutions are all relevant.

    – Robin Zigmond
    Nov 21 '18 at 13:47














  • 2





    Possible duplicate of How do I return the response from an asynchronous call?

    – Robin Zigmond
    Nov 21 '18 at 13:40











  • @RobinZigmond it is not, here we are talking about axios strictly

    – some guy
    Nov 21 '18 at 13:44






  • 1





    the specifics of the library don't matter, it's still asychronous, so the same issues and same possible solutions are all relevant.

    – Robin Zigmond
    Nov 21 '18 at 13:47








2




2





Possible duplicate of How do I return the response from an asynchronous call?

– Robin Zigmond
Nov 21 '18 at 13:40





Possible duplicate of How do I return the response from an asynchronous call?

– Robin Zigmond
Nov 21 '18 at 13:40













@RobinZigmond it is not, here we are talking about axios strictly

– some guy
Nov 21 '18 at 13:44





@RobinZigmond it is not, here we are talking about axios strictly

– some guy
Nov 21 '18 at 13:44




1




1





the specifics of the library don't matter, it's still asychronous, so the same issues and same possible solutions are all relevant.

– Robin Zigmond
Nov 21 '18 at 13:47





the specifics of the library don't matter, it's still asychronous, so the same issues and same possible solutions are all relevant.

– Robin Zigmond
Nov 21 '18 at 13:47












2 Answers
2






active

oldest

votes


















2














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





share|improve this answer


























  • Why wrap the promise that Axios returns into another one instead of using it directly?

    – Thilo
    Nov 21 '18 at 13:58











  • But how I save the promise's value and store in a variable so I can use it ??

    – some guy
    Nov 21 '18 at 13:59






  • 1





    @Thilo i know it's a weak example and i was very close not writing it, but yet i did, in case he wants to split some logic into axios then and resolve it afterwards so login().then() would be cleaner

    – darklightcode
    Nov 21 '18 at 14:01








  • 1





    I'm just worried that it makes it look like more boilerplate than there really has to be (making the callback solution look more attractive than it should be). Maybe bring up async/await as well. OTOH, it's a dupe anyway.

    – Thilo
    Nov 21 '18 at 14:02











  • @Thilo nice catch, i really forgot about async/await, i don't use it on a daily basis, i love my callback hell

    – darklightcode
    Nov 21 '18 at 14:33



















0














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





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413330%2faxios-prints-value-on-console-but-returns-undefined%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    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





    share|improve this answer


























    • Why wrap the promise that Axios returns into another one instead of using it directly?

      – Thilo
      Nov 21 '18 at 13:58











    • But how I save the promise's value and store in a variable so I can use it ??

      – some guy
      Nov 21 '18 at 13:59






    • 1





      @Thilo i know it's a weak example and i was very close not writing it, but yet i did, in case he wants to split some logic into axios then and resolve it afterwards so login().then() would be cleaner

      – darklightcode
      Nov 21 '18 at 14:01








    • 1





      I'm just worried that it makes it look like more boilerplate than there really has to be (making the callback solution look more attractive than it should be). Maybe bring up async/await as well. OTOH, it's a dupe anyway.

      – Thilo
      Nov 21 '18 at 14:02











    • @Thilo nice catch, i really forgot about async/await, i don't use it on a daily basis, i love my callback hell

      – darklightcode
      Nov 21 '18 at 14:33
















    2














    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





    share|improve this answer


























    • Why wrap the promise that Axios returns into another one instead of using it directly?

      – Thilo
      Nov 21 '18 at 13:58











    • But how I save the promise's value and store in a variable so I can use it ??

      – some guy
      Nov 21 '18 at 13:59






    • 1





      @Thilo i know it's a weak example and i was very close not writing it, but yet i did, in case he wants to split some logic into axios then and resolve it afterwards so login().then() would be cleaner

      – darklightcode
      Nov 21 '18 at 14:01








    • 1





      I'm just worried that it makes it look like more boilerplate than there really has to be (making the callback solution look more attractive than it should be). Maybe bring up async/await as well. OTOH, it's a dupe anyway.

      – Thilo
      Nov 21 '18 at 14:02











    • @Thilo nice catch, i really forgot about async/await, i don't use it on a daily basis, i love my callback hell

      – darklightcode
      Nov 21 '18 at 14:33














    2












    2








    2







    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





    share|improve this answer















    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






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 21 '18 at 14:29

























    answered Nov 21 '18 at 13:49









    darklightcodedarklightcode

    1,25699




    1,25699













    • Why wrap the promise that Axios returns into another one instead of using it directly?

      – Thilo
      Nov 21 '18 at 13:58











    • But how I save the promise's value and store in a variable so I can use it ??

      – some guy
      Nov 21 '18 at 13:59






    • 1





      @Thilo i know it's a weak example and i was very close not writing it, but yet i did, in case he wants to split some logic into axios then and resolve it afterwards so login().then() would be cleaner

      – darklightcode
      Nov 21 '18 at 14:01








    • 1





      I'm just worried that it makes it look like more boilerplate than there really has to be (making the callback solution look more attractive than it should be). Maybe bring up async/await as well. OTOH, it's a dupe anyway.

      – Thilo
      Nov 21 '18 at 14:02











    • @Thilo nice catch, i really forgot about async/await, i don't use it on a daily basis, i love my callback hell

      – darklightcode
      Nov 21 '18 at 14:33



















    • Why wrap the promise that Axios returns into another one instead of using it directly?

      – Thilo
      Nov 21 '18 at 13:58











    • But how I save the promise's value and store in a variable so I can use it ??

      – some guy
      Nov 21 '18 at 13:59






    • 1





      @Thilo i know it's a weak example and i was very close not writing it, but yet i did, in case he wants to split some logic into axios then and resolve it afterwards so login().then() would be cleaner

      – darklightcode
      Nov 21 '18 at 14:01








    • 1





      I'm just worried that it makes it look like more boilerplate than there really has to be (making the callback solution look more attractive than it should be). Maybe bring up async/await as well. OTOH, it's a dupe anyway.

      – Thilo
      Nov 21 '18 at 14:02











    • @Thilo nice catch, i really forgot about async/await, i don't use it on a daily basis, i love my callback hell

      – darklightcode
      Nov 21 '18 at 14:33

















    Why wrap the promise that Axios returns into another one instead of using it directly?

    – Thilo
    Nov 21 '18 at 13:58





    Why wrap the promise that Axios returns into another one instead of using it directly?

    – Thilo
    Nov 21 '18 at 13:58













    But how I save the promise's value and store in a variable so I can use it ??

    – some guy
    Nov 21 '18 at 13:59





    But how I save the promise's value and store in a variable so I can use it ??

    – some guy
    Nov 21 '18 at 13:59




    1




    1





    @Thilo i know it's a weak example and i was very close not writing it, but yet i did, in case he wants to split some logic into axios then and resolve it afterwards so login().then() would be cleaner

    – darklightcode
    Nov 21 '18 at 14:01







    @Thilo i know it's a weak example and i was very close not writing it, but yet i did, in case he wants to split some logic into axios then and resolve it afterwards so login().then() would be cleaner

    – darklightcode
    Nov 21 '18 at 14:01






    1




    1





    I'm just worried that it makes it look like more boilerplate than there really has to be (making the callback solution look more attractive than it should be). Maybe bring up async/await as well. OTOH, it's a dupe anyway.

    – Thilo
    Nov 21 '18 at 14:02





    I'm just worried that it makes it look like more boilerplate than there really has to be (making the callback solution look more attractive than it should be). Maybe bring up async/await as well. OTOH, it's a dupe anyway.

    – Thilo
    Nov 21 '18 at 14:02













    @Thilo nice catch, i really forgot about async/await, i don't use it on a daily basis, i love my callback hell

    – darklightcode
    Nov 21 '18 at 14:33





    @Thilo nice catch, i really forgot about async/await, i don't use it on a daily basis, i love my callback hell

    – darklightcode
    Nov 21 '18 at 14:33













    0














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





    share|improve this answer




























      0














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





      share|improve this answer


























        0












        0








        0







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





        share|improve this answer













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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 14:25









        squeekyDavesqueekyDave

        417215




        417215






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53413330%2faxios-prints-value-on-console-but-returns-undefined%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

            How to fix TextFormField cause rebuild widget in Flutter