Home > Mobile >  React map presigned URLs to state or array
React map presigned URLs to state or array

Time:12-24

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!

CodePudding user response:

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

  • Related