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.
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);
}
};