xKxAxKx
xKxAxKx

Reputation: 1074

How to update the contents of the first response with axios based on the second response

I wrote the following action in Nuxt.js.

async fetchAllCategoryPosts({ commit }) {
  await this.$axios.$get(`${process.env.apiBaseUrl}/posts/categories`).then(res => {
    for (const data of res) {
      this.$axios.$get(`${process.env.apiBaseUrl}/posts/categories/${data.category_id}`).then(posts =>{
        data['posts'] = posts
      })
    }
    console.log(res)
  })
}

The contents of res of the first request are as follows

[
  { 'category_id': 1 },
  { 'category_id': 4 },
  { 'category_id': 9 },
  { 'category_id': 11 }
]

And, based on the result, I want to send a second request and finally edit res as follows.

[
  { 'category_id': 1, 'posts': [{object}, {object} ...] },
  { 'category_id': 4 'posts': [{object}, {object} ...] },
  { 'category_id': 9 'posts': [{object}, {object} ...] },
  { 'category_id': 11 'posts': [{object}, {object} ...] }
]

However, with the above code, the result of console.log (res) has no change with the state of the first request. How can we respond?

Upvotes: 0

Views: 102

Answers (2)

pawel
pawel

Reputation: 37005

The beauty of async/await is that you can escape the "callback hell" and work with the data as if it was synchronous.

async fetchAllCategoryPosts({ commit }) {
  const categories = await this.$axios.$get(`${process.env.apiBaseUrl}/posts/categories`);
  const withPosts = await Promise.all(
    categories.map( async cat => ({ 
      ...cat, 
      posts: await this.$axios.get(`${process.env.apiBaseUrl}/posts/categories/${cat.category_id}`)
    })
  );
  return withPosts;
};

edit: I did not test this with vue/axios, but it has worked with plain es6 and substituting fetch for this.$axios.get.

Upvotes: 1

Dhananjai Pai
Dhananjai Pai

Reputation: 6005

Try the below code. I could not test this due to lack of environment, but this should work. Do let me know in case of errors


async fetchAllCategoryPosts({ commit }) {
  this.$axios.$get(`${process.env.apiBaseUrl}/posts/categories`).then(res => {
    let newRes = await Promise.all(res.data.map(async (data) => await this.$axios
      .$get(`${process.env.apiBaseUrl}/posts/categories/${data.category_id}`)
      .then(posts => ({...data, posts}));

    console.log(newRes);
  })
}

Upvotes: 1

Related Questions