创建 vuex 操作以从两个 api 服务获取合并响应 - vue

create vuex action to get the merged response from two api service - vue

我正在打两次 api 电话以创建类别明智的折扣。这里是服务

1. Api 用于类别名称(api/categories)

// 响应负载

    [
    {
        "id": 1,
        "value": "Vegetables"
    },
    {
        "id": 2,
        "value": "Foods"
    },
    {
        "id": 3,
        "value": "Clothing"
    },
]

服务

    export async function  getCategories() {
    const resp = await http.get('/categories');
    return resp.data;
}

2。 api为折扣详情(api/categories/{product_id}/discount)

// 响应负载

 [
    {
        "category_id": 2,
        "discount": 20
    },
    {
        "category_id": 3,
        "discount": 40
    },
    {
        "category_id": 1,
        "discount": 30
    }
   ]

服务

export async function  getCategoryDiscount(id) {
const resp = await http.get(`/categories/${id}/discount');
return resp.data;

}

现在,我将其调用到 vuex 操作中,并希望将这两个合并为一个状态。

喜欢的状态会是

Categories: [{ id: 1, category: "vegetables", discount: 30},{...}]

Vuex 动作(如 muka 所建议)

    async fetchCategoriesWithDiscount({commit,state}) {
     
    const productId = state.products.pros.key_details.product_id;
   const catResponse = await service.getCategories();
   const disResponse = await service.getCategoryDiscount(productId);
   console.log(catResponse,disResponse); // getting data correctly
   const allResponse = 
      Promise.all([catResponse,disResponse]).then(async(result)=> {
           const categories = await result[0].json(); // error is coming here
           const discount = await result[1].json();
           commit('updatedFetchCategories',{
              categories,
              discount
           });
       });
     console.log(allResponse);
   }

}

如何配置action使Category状态有折扣?我收到错误 "Uncaught (in promise) TypeError: result[0].json is not a function"

有一些方法可以做到这一点,具体取决于您的喜好。如果你真的想只在所有数据到达时更新状态,我建议你使用 Promise.all 方法(更多关于 Promise.all):

const initialState = () => ({
  postsWithComment: [],
})

const store = new Vuex.Store({
  state: initialState(),
  mutations: {
    UPDATE_POST(state, {
      post,
      comments
    }) {
      state.postsWithComment.push({
        ...post,
        comments,
      })
    },
  },
  actions: {
    fetchPostsAndComments({
      commit
    }) {
      const postResponse = fetch('https://jsonplaceholder.typicode.com/posts/1')
      const commentResponse = fetch('https://jsonplaceholder.typicode.com/posts/1/comments')

      // Promise.all in the action:
      const response = Promise.all([postResponse, commentResponse])
        .then(async(results) => {
          const {
            id,
            title
          } = await results[0].json()
          const comments = await results[1].json()
          commit("UPDATE_POST", {
            post: {
              id,
              title
            },
            comments
          })
        })
        // add a catch here, so you catch
        // the error of the fetches
        .catch(err => {
          console.error(err)
        })
    }
  },
})

new Vue({
  el: "#app",
  store,
  methods: {
    getPostsWithComments() {
      this.$store.dispatch("fetchPostsAndComments")
    },
  },
  template: `
    <div>
      <button @click="getPostsWithComments">GET DATA</button>
      <hr>
      {{ $store.state.postsWithComment }}
    </div>
  `
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vuex"></script>
<div id="app"></div>