How can i pass and array returned from axios in a method to the main data in vue

Please how can i send the data return from loadProducts method to products in data conponent.
i was using app.products = JSON.parse(response.data.body.data) in vue2 but now is not working in vue3. I also tried this.products but still not working

please what I’m i missing?

let app = Vue.createApp({
            data: function(){
                    return {
                        needle: "",
                        products: []
                    }
             },
methods :{
        loadProducts() {
                     axios.post('/apix/prod/load', {
                                branchID : 1,
                                invoiceCode: this.needle,
                                needle: this.needle
                                }).then(function(response){
                                    this.products= JSON.parse(response.data.body.data);
                                }).catch(function(error){
                                    console.log(error);
                                })
                    }
}

I just tested this and it is working, your code also seems to be missing a parenthesis.

<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>

<div id="app">
    {{ products }}
</div>

<script>
    createApp({
        data() {
            return {
                needle: "",
                products: []
            }
        },

        methods: {
            loadProducts() {
                this.products = ['one', 'two']
            },
        },

        created() {
            this.loadProducts()
        },
    }).mount('#app')
</script>

1 Like

Thank you for the quick response.

It works @martinzeltin inside the method but it doesn’t works/assign when it come backs from the server. i console.log the response and the data is there as expected but when I this.products=“the response” it wont assign

Your function scope is not the same as the component instance. So when you reference this within the function it isn’t the same this as the component. Simple solution is to use an arrow function.

.then(response =>
1 Like