0

I am making two requests to complete a data fetch and I am trying to get the data returned from the inner axios call out of the function.

let allArtic = [];

function articCall() {
    return axios
      .get(`https://api.artic.edu/api/v1/artworks/search?q=${searchTerm}`)
      .then((res) => {
        res.data.data.map((entry) => {
          axios
            .get(
              `https://api.artic.edu/api/v1/artworks/${entry.id}?fields=id,title,image_id`
            )
            .then((res) => {
              const url = `${res.data.config.iiif_url}/${res.data.data.image_id}/full/843,/0/default.jpg`;
    
              const artObj = {
                name: searchTerm,
                title: res.data.data.title,
                img: url,
              };
    
              allArtic.push(artObj);
              return allArtic;
            });
        });
      })
      .catch((error) => {
        console.log(error);
      });
}

console.log("all", allArtic); // => GET desired data

I have done a similar approach with a single axios call and it has worked. I tried to add the data in each iteration to an outside array but this has resulted in an empty array.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • Use `return` on all those nested functions, just as you `return axios` in the top level function. Use `Promise.all` around the `map`, to await the resolution of a list of promises. – deceze May 29 '23 at 05:06

0 Answers0