Victor Gorban
Victor Gorban

Reputation: 1699

Cannot read property 'data' of undefined inside promise. At a very strange place

I don't know how to call it.

Two funcitons in my object:

login: (credentials) => {
    console.log('im in login user');

    axios.post('/api/auth/login', credentials)
            .then(res => {
                console.log(res.data);
                return res.data;
            }).then(
            (toStore) => {
                this.store('hey'); // When I remove this, all OK
            })
            .catch(error => {
                console.log(error.response.data);
                return false;
            })
},

store: (something) => {
    console.log('in user. store');
    // localStorage.setItem(this.storageKey, dataToStore);
},

But look at the this.store('hey'); line. When I remove it, I can't see the error. When I have it, I have the error. But what data does the error mean? error

Ok, I found the problem. Error doesn't have response property. And I getting the error because of... It was an object, not a class. As I converted the object to class, It's OK now.

Upvotes: 0

Views: 2396

Answers (3)

Victor Gorban
Victor Gorban

Reputation: 1699

Ok guys, thanks to everyone, I found all the errors in my code. There was two of them:

  1. error.response is not defined (There's no such property). Proper line should be console.log(error);.

  2. Also, because of arrow-functions behavior (scope issue), the login function couldn't see my store function.

In fact, I got error #2 in second then statement, so that led my program inside catch statement, where was error #1.

Upvotes: 0

mkl5915
mkl5915

Reputation: 56

The problem is the behavior of this in arrow functions.

If you replace login: (credentials) => {} with login: function (credentials){}, then this.store('hey') should work.

Upvotes: 1

cWerning
cWerning

Reputation: 633

error.response is undefined. That's why you're getting "Cannot read 'data' of undefined".

To protect yourself from this error, I would try the following code...

        .catch(error => {
                console.log( (error.response || {}).data );
                return false;
            })

However, the underline reason why you're not seeing the error when you remove this.store('hey') is a different problem. It seems to be a scope issue. Try removing "this."

Upvotes: 2

Related Questions