Home > Back-end >  How can I do two Axios GET requests, map the result and then pushing that to an array?
How can I do two Axios GET requests, map the result and then pushing that to an array?

Time:12-22

I have a hard time understanding promises and in this case with Axios. I've been reading up about it and searched stackoverflow endlessly but still can't wrap my head around it.

Firstly, I'm trying to get a list of exercises, and in that result there is an ID(called exercise_base). That ID i want to use to make another GET request to receive the images for that exercise.

Then, I'm pushing the name, id, and the image as an object to an array. It works perfectly to get the list of exercises and push that to an array, but when trying to get the images I can't seem to get it working.

In my object, I want to pass the imageUrl that I receive from my getImages promise. How can I achieve this?

function getImages(exercise_base) {
  return axios.get("https://wger.de/api/v2/exerciseimage/?exercise_base="   exercise_base);
}

const fetchData = async () => {
  const result = await axios(getFetchUrl());
  const array = [];
  // mapping through all the exercises, getting the exercise_base id which i then pass my getImages function
  result.data.results.map(({
    name,
    id,
    category,
    description,
    exercise_base
  }, e, index) => {
    getImages(exercise_base).then((e) => {
      // I want to pass this as imageUrl: in my object
      console.log(e.data.results[0].image);
    });
    array.push({
      value: name,
      description: "description",
      category: category,
      key: id,
      imageUrl: "" // Here I want to pass my imageUrl that I get from my getImages promise.
    });
  });
};

CodePudding user response:

Create a single promise that resolves when all the inner promises resolve using Promise.all(). The resolution of each inner promise can be the fully hydrated object

const EXERCISE_IMAGE_URL = "https://wger.de/api/v2/exerciseimage/"

const getMainImage = async (exercise_base) => {
  const { data: { results } } = await axios.get(EXERCISE_IMAGE_URL, {
    params: { exercise_base } // using params is safer
  })

  // resolve with the first _main_ image (or undefined if none)
  return results.find(({ is_main }) => is_main)?.image
}

const fetchData = async () => {
  const { data: { results } } = await axios(getFetchUrl());

  // map each result to a new promise that resolves with the full object
  return Promise.all(results.map(async ({
    name,
    id,
    category,
    description,
    exercise_base
  }) => ({
    value: name,
    description,
    category,
    key: id,
    imageUrl: await getMainImage(exercise_base)
  })))
}
  • Related