0
votes

I am working on a vue project where I am using vuex for managing state. I have defined state, actions, mutations as well as dispatch to call the action. But the problem is, I am getting an error near dispatch like Cannot read property 'getProduct'(action name) of undefined at Store._callee.

Can anyone guide me where I am doing wrong?

Here is my code:

Dispatch action from component:

async created() {
  try {
     await this.$store.dispatch("getProduct");
  } catch (error) {
     console.log("Error", error);
  }
}

Actions code:

Here in ProductService, I have getProduct() function where I am performing API call.

const actions = {
   async getProduct({ commit }) {
      commit("GET_PRODUCT", await ProductService.getProduct());
   }
}

Mutation code:

const mutations = {
   GET_PRODUCT: (state, product) => {
      state.product = product;   // Here I am mutating the state
   }
}
1
At the top of your getProduct action could you put console.log(ProductService), to confirm whether that gets called and whether ProductService is actually defined? - skirtle
this is unrelated, but this is wrong commit("GET_PRODUCT", await ProductService.getProduct()); commits are sync operations. You need to wait and then commit const res = await ProductService.getProduct() commit("GET_PRODUCT", res) - Radu Diță
Hi @skirtle,Thank you for your quick response and this is working what you told. - Dcoder14
@RaduDiță, If you can see official site, there is an example as -> actions: { async actionA ({ commit }) { commit('gotData', await getData()) }, async actionB ({ dispatch, commit }) { await dispatch('actionA') // wait for actionA to finish commit('gotOtherData', await getOtherData()) } } - Dcoder14
You are right, my bad - Radu Diță

1 Answers

0
votes

After debugging a long time, I got to know that there was an error in service function 'ProductService.getProduct()' inside action code. Here in my case I have created service file named 'ProductService' in which I have defined functions for API calls and 'getProduct()' is one of the functions where API call is done to get list of products.

While I tried to print whether this function call is returning values or not and this was returning undefined and for that the above error was coming. Then I fixed issue in service function for which this function call returns undefined and after that it works fine.

Error was in below line of code.

commit("GET_PRODUCT", await ProductService.getProduct());

Thanks @skirtle and @Radu Diță for your comments.