1

I'm trying to run a method when I get success response from API, but the method dont run. I made a quick example here to show.

The test() function should be executed after i get the response, since its calling another API endpoint. Here is the vue.js code.

var app = new Vue({
    el: "#contents",
    data: { 
        id: null,
        details: [],
    },
 
    methods: {

        fetchProductDetails: function(){
            let vue = this;
            axios.post("/api/get-details", {
                id : id
            })
            .then(function (response) {
                vue.details = response.data;
                this.test();
            })
            .catch(function (error) {});
        },
    
        test: function () {
            console.log(app.details);
        }
    },
    mounted: function(){
        this.fetchProductDetails();
    },

});
2
  • Using function (response) in your .then most likely breaks the scope of this. Have you tried using the ES6 arrow syntax? Commented Jul 30, 2020 at 8:48
  • Not tested ES6 syntax, my values come out as "null" Commented Jul 30, 2020 at 8:54

1 Answer 1

1

You should run vue.test() instead of this.test(), just like you use vue.details = response.data instead of this.details = response.data.

When using an unnamed function in .then(), this no longer refers to your vue application, but to the unnamed function. You could use ES6 arrow function syntax in order to avoid having to set this to a specific variable, as arrow functions use their parent's scope for this instead of setting this to refer to themselves:

axios.post("/api/get-details", { id: this.id })
            .then(response => {
                this.details = response.data;
                this.test();
            })
            .catch(error => { console.log(error)});

Arrow functions (and ES6 in general) are not supported by IE11 however. so you'd need to use Babel to compile it back to something ES5 JavaScript if you need to support older browsers.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, i supose i should use this format on api calls in the future then!
If your target browsers support it (or it's handled by a tool chain that compiles it to older syntax), definitely! I personally like to use async/await instead of then/catch, and object destructuring to immediately reach into objects for the key I need as well: async fetchProductDetails() { try { const { data } = await axios.post(/api/get-details, { id: this.id }); this.details = data; this.test(); } catch (e) { console.log(e); } }

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.