f / vue-wait

Complex Loader and Progress Management for Vue/Vuex and Nuxt Applications
MIT License
2k stars 101 forks source link

alternative for startLoading in Vuex actions? #46

Closed kjakobson closed 6 years ago

kjakobson commented 6 years ago

I was using previous startLoading decorator function and I don't understand how it can be replaced from the new documentation. Can you maybe point me to the right direction?

Here is my example usage with vuex-loading:

dispatch('setActivities', await startLoading(dispatch, 'fetch activities', () => Activity.fetchAll()))
f commented 6 years ago

I encourage you to use mapWaitingActions instead.

import { mapWaitingActions } from 'vue-wait';

// in your component

methods: {
  ...mapWaitingActions({
    setActivities: 'fetch activities',
  })
}

When you call this.setActivities your setActivities action will be called.

In your store you should only call your async function:

actions: {
  async setActivities() {
    return await Activity.fetchAll();
  }
}
kjakobson commented 6 years ago

I tried it. But do I have to map actions with mapWaitingActions in every component again? Perhaps fetchActivities is not the best example, since you call it usually once in app. But let's say you have multiple components which can call saveActivity. Do I have to write action mapping for each of them?

kjakobson commented 6 years ago

I ended up with this to avoid repeating code:

async fetchActivities ({ dispatch }) {
    try {
      dispatch('wait/start', 'fetch activities', { root: true })
      dispatch('setActivities', await Activity.fetchAll())
      return Promise.resolve()
    } catch (error) {
      console.error(error)
      return Promise.reject(new Error('Could not fetch activities'))
    } finally {
      dispatch('wait/end', 'fetch activities', { root: true })
    }
  }