JacobVin
JacobVin

Reputation: 37

My Vue.js code about Axios and function is not working

I want to execute function2 after axios. I got no catch error. but still Function2 is not executed.

The code i want but not working :

   add: function () {
        axios.post('/add', this.person)
            .then(response => {
               if (response.data.etat) {
                    this.person = {};
                    this.function2();
                }
            })
            .catch(error => {
                console.log('errors: ', error)
            })},

This is working, but i would like to execute function2 only if axios pass.

add: function () {
        axios.post('/add', this.person)
            .then(response => {
               if (response.data.etat) {
                    this.person = {};

                }
            })
            .catch(error => {
                console.log('errors: ', error)
            })
             this.function2();
             },

Any help ? thank you !

Upvotes: 2

Views: 41

Answers (2)

Beniamin H
Beniamin H

Reputation: 2086

You can chain .then() blocks:

add: function () {
        axios.post('/add', this.person)
            .then(response => {
               if (response.data.etat) {
                    this.person = {};
                }
            })
            .then(() => {
               this.function2();
            })
            .catch(error => {
                console.log('errors: ', error)
            })
}

this.function2 will be called only if your axios.post is successful and if the first .then() doesn't throw any error. In another case - your .catch() will catch the error.

Here you can see how it works on live: https://codepen.io/anon/pen/gZQyym?editors=1111

Upvotes: 2

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Since you're using axios to post data, and you want to do call that method after the operation is done successfully so you should check the response status like :

   add: function () {
    axios.post('/add', this.person)
        .then(response => {
           if (response.status==200) {
                this.person = {};
                this.function2();
            }
        })
        .catch(error => {
            console.log('errors: ', error)
        })},

Upvotes: 1

Related Questions