Cannot read properties of undefined (reading 'then') when trying to use a 'then' promise

Advertisements

I am currently constructing a login page using reactjs. The login page takes the users details and passes them to an API object that has an authorise function which authorises the users’ details. Within the login component, after getting the details, I have a call to the authorise function which looks like this:

const api = new API();
api.authorise(email, password, appid).then((result) => {
    if (result.status === 200) {
        console.log("Auth Successful");
        return result;
    } else {
        console.log("Auth Failed")
        return result;
    }
});

However, when this call is run, it successfully reaches the ‘authorise’ function but gives an ‘Uncaught TypeError: Cannot read properties of undefined (reading ‘then’), and I am struggling to figure out why. The authorise function can be seen below (Uses Axios to send requests):

authorise(email, password, appid) {
    this.email = email;
    this.password = password;
    this.appid = appid;

    let url = "api url";

    const data = {
        "data1": email,
        "data2": password,
        "data3": appid
    }

    axios.post(url, data).then((res) => {
        return res;
    }).catch((err) => {
        return err;
    })
}

I have already tried to declare the authorise function as such: authorise = (email, password, appid) => {} But that did not work. Any advice on how to stop this error or restructure the promise call would be much appreciated. Thanks in advance.

>Solution :

You forgot return promise ..

authorise(email, password, appid) {
    this.email = email;
    this.password = password;
    this.appid = appid;

    let url = "api url";

    const data = {
        "data1": email,
        "data2": password,
        "data3": appid
    }

    return axios.post(url, data)
}

Leave a Reply Cancel reply