user5283666
user5283666

Reputation:

Why is this promise not resolving back to the caller?

I have a Vue-App which runs with Vuex and Axios. In this app I have vuex-store which handles API-calls, but a problem is that when I call the store-actions I cant chain the response in the caller.Any ideas what Im doing wrong?

Calling code:

import { FETCH_PRODUCTS, ADD_PRODUCT } from './actions.type'

methods: {
    sendNewProduct () {
      this.$store
        .dispatch(ADD_PRODUCT, this.newProductForm)
        .then(() => {
          console.log('This never gets called')
        })
    }
  }

Vuex-store:

const actions = {
  [ADD_PRODUCT] (context, credentials) {
    return new Promise((resolve) => {
      ApiService
        .post('/Products/', {
          Name: credentials.Name,
          Description: credentials.Description,
          Price: credentials.Price
        })
        .then(({ data }) => {
          this.$store
            .dispatch(FETCH_PRODUCTS)
            resolve(data)
        })
        .catch(({ response }) => {
          console.log(response)
          context.commit(SET_ERROR, 'Error adding product')
        })
    })
  }
}

Upvotes: 1

Views: 72

Answers (1)

Bob Fanger
Bob Fanger

Reputation: 29897

const actions = {
  [ADD_PRODUCT](context, credentials) {
    return ApiService.post("/Products/", {
      Name: credentials.Name,
      Description: credentials.Description,
      Price: credentials.Price
    })
      .then(({ data }) => {
        this.$store.dispatch(FETCH_PRODUCTS);
        return data;
      })
      .catch(({ response }) => {
        console.log(response);
        context.commit(SET_ERROR, "Error adding product");
        throw new Error("Error adding product");
      });
  }
};

I've removed the new Promise(...) because axios already creates a promise. If added a return data in the then callback and a throw in the catch callback to let the calling api receive the data/error.

Note that the promise resolves before the FETCH_PRODUCTS completes, to make sure that action is also completed, you'd write:

.then(({ data }) => {
  return this.$store.dispatch(FETCH_PRODUCTS)
    .then(() => data);
})

Upvotes: 0

Related Questions