Axios response data is undefined while the request is succesful

arthur-sh
    function confirmPassword() {
    let password = document.getElementById("password").value
    let email = document.getElementById("email").value

    Service.confirmPassword(email, password).then(response => {
        res = response.data
        setTwoFactorStep(1)
    }).catch(err => {
        alert(err.data.message)
    })
    alert(res)
}  

After the request is done, response.data is undefined, while I can check my browser it was succesful, and the body is present. If I alert response.data inside the .then I get an Object object

OBS: The var res is declared before, and the method Service.confirmPassword is a axios.post.

the_makeshift_dev

The code you have posted isn't synchronous the alert will trigger before your http request has a chance to resolve which is probably why you get an undefined. if you want to do anything with the response body you should probably do it within the 'then' callback.

function confirmPassword() {
    let password = document.getElementById("password").value
    let email = document.getElementById("email").value

// 1.your service call through axios gets triggered
    Service.confirmPassword(email, password).then(response => {
      // 3.this gets execute after the alert below once the http request has been resolved
        res = response.data 
        setTwoFactorStep(1);
    // invoke your handler here...
    }).catch(err => {
        alert(err.data.message)
    })
    alert(res) // 2.this gets executed next
}  

if you want to write this in a synchronous way, consider using async/await

 async function confirmPassword() {
    let password = document.getElementById("password").value
    let email = document.getElementById("email").value

    const response = await Service.confirmPassword(email, password).catch(err => alert(err.data.message));
    res = response.data;
    setTwoFactorStep(1);
    alert(res)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related