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?

1

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.