0

I am new to Reactjs. I have created an app to upload multiple files to aws s3. I am using a loop to upload all files. I also need to get response from the uploaded file like the filename. This is what I have till now:

const handleClick =  async (event) => {
event.preventDefault();
let newArr = fileInput.current.files;
for (let i = 0; i < newArr.length; i++) {
  const file = newArr[i]
  let newFileName = file.name.replace(/\..+$/, "");
  const ReactS3Client = new S3(config);
  ReactS3Client.uploadFile(file, newFileName).then((data) => {
    if (data.status === 204) {
      console.log( data.key);
    } else {
      console.log("fail");
    }
  });
}

  };

After a lot of googling, I added async to my handleclick. I am super confused. Can anyone please tell me how to wait for the loop to finish? Or just wait for handClick to execute completely? My key also shows undefined if I try to print it out. I can only get response in the .then in handleUpload. But i need to wait for all keys before I can make another api call and change page. Any help is appreciated.

Ninad Gaikwad
  • 4,272
  • 2
  • 13
  • 23
  • 1
    https://stackoverflow.com/questions/31426740/how-to-return-many-promises-and-wait-for-them-all-before-doing-other-stuff – Lukas Sep 18 '21 at 17:10

1 Answers1

1

First thing, you are doing this in the wrong way. ReactS3Client (in your case) should be initialized once.

And about the question you asked. You can use Promise.all().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

Use it like this.

// Import from other file like config
const ReactS3Client = new S3(config);

const handleClick = async (event) => {
  event.preventDefault();
  try {
    const newArr = fileInput.current.files;
    const v = await Promise.all(
      newArr.map(async (file) => {
        let newFileName = file.name.replace(/\..+$/, "");
        // assuming key is there in response
        const { key } = await ReactS3Client.uploadFile(file, newFileName);
        return {
          newFileName,
          fileKey: key,
        };
      })
    );
    console.log(v);
  } catch (e) {
    console.error(e);
  }
};
Joel Jaimon
  • 202
  • 3
  • 10
  • Thank you for your answer. I tried this but now I am getting this error: `TypeError: newArr.map is not a function at handleClick (Form.js:38)` Any idea what I am doing wrong? – Ninad Gaikwad Sep 18 '21 at 17:29
  • Check your ref that you've used for the input tag. – Joel Jaimon Sep 18 '21 at 17:31
  • I think the problem was that newArr was filelist. I converted it to array and it is working now. Thanks a lot! I can finally sleep – Ninad Gaikwad Sep 18 '21 at 17:41