0

I am trying to handle the uploading of images in a form, in order to convert them to base64 and store them as strings in an string[]. For this, Im using FileReader and its method readAsDataURL. When I execute the program, it does not store the strings but if I debug the program, it does. I have no idea why this is happening? Does anybody have any clue?

This is my code, Im using react and TypeScript.

<Input 
      type="file" 
      accept='image/*' 
      onChange={(e) => {
         var reader = new FileReader();
         let files = e.target.files !== null ? e.target.files : [];
         for (let image of files){
              reader.readAsDataURL(image)
              reader.addEventListener("load", function () {
                  let srcImage = reader.result;
                  imgs.push(srcImage as string)
              })
         }
      }} 
      multiple>
</Input>

'imgs' is a global string[] variable in which i am trying to store the base64 representation of the images.

  • Please show how you're *using* `imgs`. You're almost certainly running into [this problem](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). – T.J. Crowder Mar 27 '23 at 16:58
  • I only access to 'imgs' when doing the push, to add a string. Then I use it in another component to store it in a pod (the Solid Project). Is that what you were asking for? – Patricia García Mar 27 '23 at 17:03
  • It's the "using it in another component" part that we're interested in. There doesn't seem to be anything in the above that would let you coordinate that with the asynchronous process of reading the data (see the link above). – T.J. Crowder Mar 27 '23 at 17:22
  • Im working on this repository https://github.com/Arquisoft/lomap_en2a in the branch solid-store-patri, maybe you could help me if you can? – Patricia García Mar 27 '23 at 17:29

0 Answers0