0

I am doing a file upload operation in React, and I need to read the file uploaded from the user and do some state changes according to this file. What I have right now is shown below and I need to need to access the variable startInt within the onload callback, but it is still not defined here using the IIFE

const file = document.getElementById("fileUpload").files[0];
if (file) {
  const reader = new FileReader();
  reader.readAsText(file, "UTF-8");

  reader.onload = ((theFile) => {
    const form = document.getElementById('fileUploadForm');
    const start = datetimeToISO(form.Start.value);
    const startInt = new Date(start).getTime();

    return (e) => {
      console.log(e.target.result);
      //startInt is not defined here
    }
  })(file);
}

I followed this guide if it helps: https://stackoverflow.com/a/16937439/6366329

If you could point out my mistake that would be great. Many thanks in advance

singard
  • 107
  • 3
  • 10

1 Answers1

1

you can access local var (but not class const like this.state.* or this .props.*). so something like this you need:

    var file = document.getElementById('inputID').files[0]
    var Images = this.props.motherState.Images // Images is array 
    var reader = new FileReader();
    reader.readAsDataURL(file); //

    reader.onload = function () {
        //console.log(reader.result);
        if (file.type.match(/image.*/))           
            Images.push(reader.result) // its ok
        // but  this.props.motherState.Images.push(reader.result)
        // return error like this:
        // Images not define in this.props.motherState.Images
    };



    reader.onerror = function (error) {
        //console.log('Error: ', error);
    };