-1

I am trying to figure out a way to basically setState for the fileName and contents of the file when the user selects the file. Or if not setState, call another method as shown below

performFileUpload() {
    
    var tempFileName: string;
    let input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xml';    
    input.addEventListener("change", function() {
      const file = this.files[0];
      tempFileName = this.files[0].name;
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onerror = reject;
      reader.onload = function (evt) {
        let result = evt.target.result.toString();         
        //TODO: Have a way to setState({fileName:tempFileName, selectedFile: result})
        //Or simply call postNewFile(tempFileName, result);
      };
      input.click();    
    }) 
  }

postNewFile(nameOfJrfl: string, selectedJrfl: string) { //Send a post }

  • Aside from `setState` not being defined in the code you've shared, it isn't clear what the problem with the commented out code is. – Quentin Aug 28 '23 at 17:33
  • The problem is it won't let me setState in that method because it is async – John Grove Aug 28 '23 at 17:42
  • What about this `setState` method, which you still have not shared with us, prevents it being called from an async function? – Quentin Aug 28 '23 at 17:43
  • You should probably read [ask] and the [question checklist](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) – Quentin Aug 28 '23 at 17:45
  • The FileREader.onload will not let me call any of my methods or setState. I am just trying to figure how to set state in that or call a method. I was trying to wrap the result in a Promise, but not sure how to do that. This is React, if you don't know what SetState is, why are you responding? – John Grove Aug 28 '23 at 17:48
  • You didn’t tag the question [tag:react] or even mention React before that comment, so why are you being insulting about me not assuming you are using React? – Quentin Aug 28 '23 at 18:18
  • You haven’t even given a clear description of the problem. “Won’t let me” doesn’t resemble the quoted text of an error message at all. – Quentin Aug 28 '23 at 18:19
  • Probably a duplicate of https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – Quentin Aug 28 '23 at 18:20

0 Answers0