Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading multiple files cotent's React JS

I'm trying to read multiple files with React.js, but my code reads only one file and doesn't read the rest. Any suggestion?

Thanks

constructor(props) {
    super(props);
    this.state = {
        files: [],
        changedFileIndex: -1,
        fileReader : null
    };
    this.fileUploaderRef = React.createRef();
}

 handleFileReader = (e)=>{
    console.log("handleFileReader")
     var content =this.state.fileReader.result;
     console.log(content);
 }

  handleFileChosen(file){
    console.log("handleFileChosen")
    console.log(file.result)
     this.state.fileReader=new FileReader();
     this.state.fileReader.onloadend = this.handleFileReader;
     this.state.fileReader.readAsText(file);   

 }


async readAllFiles (AllFiles) {
    console.log("readAllFiles")
    //console.log(AllFiles[0].name)
   AllFiles.map((file)=>
       {  
               this.handleFileChosen(file)
        }
    );

 }

In the array of files, we need to loop over the files and send to the other functions in order to write content of each file in the array. After some debugging, for example for 2 files, it looks like the code executes 'handleFileChosen' 2 times, and then goes to handleFileReader 2 times which is probably what's wrong but I'm not sure how to fix this. Instead, it should be like this: execute 'HandleFileReader', then execute 'handleFileChosen', then again 'HandleFileReader', then execute 'handleFileChosen'

like image 268
Bhaa Rizik Avatar asked Oct 30 '25 12:10

Bhaa Rizik


1 Answers

arr.map() is synchronous and FileReader works asynchronously, use Promise.all on the array returned by map

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

I have modified your functions to read all files

handleFileChosen = async (file) => {
  return new Promise((resolve, reject) => {
    let fileReader = new FileReader();
    fileReader.onload = () => {
      resolve(fileReader.result);
    };
    fileReader.onerror = reject;
    fileReader.readAsText(file);
  });
}


readAllFiles = async (AllFiles) => {
  const results = await Promise.all(AllFiles.map(async (file) => {
    const fileContents = await handleFileChosen(file);
    return fileContents;
  }));
  console.log(results);
  return results;
}
like image 71
Nagesh Sanika Avatar answered Nov 01 '25 02:11

Nagesh Sanika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!