So i'm fetching images from a remote server. then converting these images to base64 and pushing them to an empty array. the problem is the array length outside of that function doesn't get updated. i'm pretty sure it has to do something with the async/await function.
here's my code
const handleSubmit = async (listing) => {
const product = {files:[]};
const getBase64StringFromDataURL = (dataURL) => dataURL.replace('data:','').replace(/^.+,/, '');
for (let image of listing.images) {
await fetch(image)
.then((res) => res.blob())
.then((blob) => {
// Read the Blob as DataURL using the FileReader API
const reader = new FileReader();
reader.onloadend = () => {
const base64 = getBase64StringFromDataURL(reader.result);
product.files.push(base64)
// here the product.files length is updated without a problem
console.log(product.files.length)
};
reader.readAsDataURL(blob);
});
}
// here the length is 0
console.log(product.files.length)
}
please help figure this out. i'm open to a better alternative !