Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React map presigned URLs to state or array

I have an async function that returns presigned URLs as a Promise and I want to get the URLs as a list from these Promises. This works fine for one URL as an input but I want to give the async function a list of URLs in order to get a list of presigned URLs.

function ImgGallery() {
  const [url, setUrl] = useState([]);
  const imglink = ['https://link1.jpg', 'https://link2.jpg'];

  useEffect(() => {
    imglink.map(i => {
      fetchImages(i).then(setUrl)
    })
  }, []);
  console.log(url);

I get only 'https://presigned_link2.jpg' as an output but I want to get ['https://presigned_link1.jpg', 'https://presigned_link2.jpg']. I know that I overwrite the state every time and get therefore only the last value in my array but I don’t know how to solve this. I also tried some solutions with concat but it does not work.

Thanks in advance!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could do something like:

function ImgGallery() {
  const [url, setUrl] = useState([]);
  const imglink = ["https://link1.jpg", "https://link2.jpg"];

  useEffect(() => {
    const promises = imglink.map((i) => {
      return fetchImages(i);
    });

    Promise.all(promises).then((responses) => {
      setUrl(responses);
    });
  }, []);

  console.log(url);
}

So promises is an array of promises and then we just use Promise.all to wait for all of them to finish. So long as fetchImages returns a promise

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading