0

I have the following code in which I'm reading the base64 versions of files using FileReader. The variable formValues contains a property "images", which contains an array of Files (i.e., File info and local url). I update the images property to contain the base64 strings rather than the Files at the end of the method. However, the console log at the beginning of the method is showing that update. When I comment out the update at the end, the console log at the beginning again shows the Files. How strange. What am I doing wrong?

    const confirm = () => {

        console.log("form values in confirm");
// this prints the base64 string when formValues["images"] = images
// is present at the end. 
// Otherwise it prints the Files.  
        console.log(formValues.images); 

        let images = [];
        for (let i = 0; i < formValues.images.length; i++) {
            var reader = new FileReader();
            reader.onload = function(e) {
                images.push(e.target.result);
                console.log('images base 64');
                console.log(images);
            };
            reader.readAsDataURL(formValues.images[i].file);
        }
        formValues["images"] = images;
        console.log("values after adding images");
        console.log(formValues);

    };

zengod
  • 1,114
  • 13
  • 26

1 Answers1

0

That's because arrays are mutable, which means their values can change after they are created.

Addis
  • 2,480
  • 2
  • 13
  • 21