0

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!

sgsikuga
  • 3
  • 2
  • Does this answer your question? [Push method in React Hooks (useState)?](https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate) – Matt U Dec 23 '21 at 18:17
  • Thank you for the quick answer. I tried it but I do not get an array in my output but distinct prints. When I try to access an entry like `url[0]` it does not work. – sgsikuga Dec 23 '21 at 18:39

1 Answers1

1

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

Meeoh
  • 463
  • 4
  • 11
  • Thank you for your quick answers. I have tried the solution but my variable `url` returns `Array [ undefined, undefined ]`. I really don't understand what I'm missing. – sgsikuga Dec 23 '21 at 18:38
  • hmm, can we see how `fetchImages` is implemented? – Meeoh Dec 23 '21 at 18:40
  • I just realized a typo in my code, can you look at it again? I was missing the return statement inside the map where I was calling fetchImages – Meeoh Dec 23 '21 at 18:40