0

I am trying to disable loading when the HTTP request returns an error, but it gives me this error.

Uncaught (in promise) TypeError: Cannot set property 'loading' of undefined

Code

    export default {
        name: 'login',
        data() {
            return {
                loading: false, //can't be set to false on request error
            }
        },
        methods: {
            login: function () {
                this.loading = true;
                const { username, password } = this
                this.$store.dispatch('login', { username, password }).then((resp) => {
                    setTimeout(() => {
                        this.loading = false;
                    }, 5000);
                    // this.$router.push({name: 'dashboard'})
                }).catch(function (error) {
                    this.loading = false; // Uncaught (in promise) TypeError: Cannot set property 'loading' of undefined
                    console.log('error', error);
                });
            }
        }
    }

Any idea?

Momin
  • 3,200
  • 3
  • 30
  • 48
mafortis
  • 6,750
  • 23
  • 130
  • 288
  • Does this answer your question? [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Phil Jul 02 '20 at 04:27

1 Answers1

2

this represent to the object that called the function in catch method, not to the current vue component.

so either you can use var vm=this outside and use after like below.

  login: function () {
        this.loading = true;
        var vm = this;
        .....
        .....
        }).catch(function (error) {
            vm.loading = false;
            console.log('error', error);
        });
    }

Or use arrow method

  login: function () {
        .....
        .....
        }).catch((error) => {
            this.loading = false;
            console.log('error', error);
        });
    }

You already used arrow method with setTimeout in below code, so I guess you aware of this, just use this to fix this also

setTimeout(() => {
    this.loading = false;
}, 5000);
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109