[Vuejs]-Vue: Component method from vuex module?

0👍

Two issues:

  • You need to return the promise from the action so that you can use .then() to schedule code to be executed once the action has completed (this code being whatever you need to do to clear the form).
  • .then() takes one (or two) functions as parameters which will be called once the promise has resolved, instead you’re just calling alert() immediately.

It’ll be something like:

Component method

stripeSourceHandler(sourceId) {
  if (this.customerSources.length == 0) {
    this.createSourceAndCustomer({ id: sourceId });
  } else {
    this.addSource({ id: sourceId }).then(() => {
      // Clear the form here
      alert('Form cleared');
    });
  }
}

Vuex action

addSource({ commit }, sourceId) {
  commit('Loader/SET_LOADER', { status:1, message: 'Procesando...' }, { root: true });

  // Return the promise here
  return axios.post('/stripe/add-source', sourceId)
    .then(response => {
      commit('Loader/SET_LOADER', { status:2, message: response.data.message }, { root: true });
      commit('ADD_SOURCE', response.data.customer);
    }, error => {
      commit('Loader/SET_LOADER', { status:3, errors: error, message: 'Error al añadir el pago.' }, { root: true });
    });
}

Leave a comment