christianmalek / vuex-rest-api

A utility to simplify the use of REST APIs with Vuex
http://vuex-rest-api.org
MIT License
382 stars 48 forks source link

can we have a onSuccess from inside the component? #63

Closed vesper8 closed 6 years ago

vesper8 commented 6 years ago

Right now my vuex module looks like this

/* eslint-disable no-param-reassign */
import Vapi from 'vuex-rest-api';

const nav = new Vapi({
  baseURL: '/api',
  state: {
    nav: {},
  },
})
  .get({
    action: 'getNav',
    property: 'nav',
    path: ({ season }) => `/nav?season=${season}`,
    onSuccess: (state, payload) => {
      state.nav[payload.data.currentSeason.slug] = payload.data;
    },
  })
  .getStore();

export default nav;

And my component includes this:

  computed: {
    ...mapState({
      nav: state => state.nav.nav,
      pending: state => state.nav.pending,
      error: state => state.nav.error,
    }),
  },
  methods: {
    ...mapActions(['getNav']),

    loadNav() {
        this.getNav({ params: { season: this.currentSeason } });
    },

I struggle to perform an action when the call to this.getNav has completed.

I have tried setting a watcher on pending.nav which kind of works but produced some bad results. And I could maybe do it by setting a state inside the vuex module and then adding a watcher on that. But really what would work a lot better is if I could add an onSuccess directly inside the loadNav() method above. Because really what I want to do is perform an action on the component itself once the getNav is done loading the api results into the vuex state

Is it possible to do this? If so I would love to see an example please!

christianmalek commented 6 years ago

Hi!

Every actions returns an promise. So you could catch errors with try-catch like this:

async loadNav() {
  try {
    await this.getNav({ params: { season: this.currentSeason } });
    // success
  } catch (error) {
    // error
  }
}

Alternatively use then() and catch().

vesper8 commented 6 years ago

hey wow! that's awesome! i've never had a chance to use async/await until now but wow that just works! it's magic! very useful indeed!!

thanks for showing me!