I have the following code in which I'm trying to read a file using FileReader and put its contents in an array. Only after all the data has been pushed do I want to continue. Here's what I have currently:
const confirm = () => {
var reader = new FileReader();
let images = [];
reader.onload = function(e) {
images.push(e.target.result);
};
reader.readAsDataURL(formValues.images[0].file);
console.log('images base 64');
console.log(images); // this prints the empty array.
};
I want to continue on only after images have been updated with the file contents. How can I do that?
-- edit --
I want to in fact add multiple files to the array, so I tried the following.
var reader = new FileReader();
let images = [];
reader.onload = function(e) {
images.push(e.target.result);
console.log('images base 64');
console.log(images);
};
for (let i = 0; i < formValues.images.length; i++) {
reader.readAsDataURL(formValues.images[i].file);
}
But this gives the error "InvalidStateError: The object is in an invalid state."