How to return Promises from Vuex actions

September 6, 2019

Vuex actions are asynchronous. So you are calling actions from your Vue component there should be a way to to know that the action you called , is completed successfully or not. So, the best way to do is, wrap your action around promises

I have the following code in my store.js file

actions: {

getProductTable(context, data) {
            return new Promise((resolve, reject) => {
                
                axios.defaults.headers.common['Authorization'] = 'Bearer '+ context.state.token
                axios.get("api/products?page="+data.page).then(response => {
                    
                   

                    resolve(response);  
                }, error => {
                    
                    reject(error);
                })
            })
        },


}

In this example, I am calling getProductTable action in my ProductTable.vue file

 this.$store.dispatch('getProductTable',{page:this.page})
         .then(response=>{
             this.products = response.data.data;
           
         })