-1
   onReaderLoad = (e) => {
    var obj =JSON.parse(e.target.result)
    this.setState(prevState => ({
      datasource: [...prevState.datasource, obj]
    }))
  }

  ReadFiles = () => {
    let files = this.state.json_files;

    for (let i of files){
      var reader = new FileReader();
      reader.onload = this.onReaderLoad;
      reader.readAsText(i);
    }

    console.log(this.state.datasource)

  }


  getfolder = (e) => {
    var files = e.target.files;
    this.setState({
      json_files: files
    }, () => this.ReadFiles())    
  }


                  <input type="file" onChange={this.getfolder} multiple accept=".json" />

Here i am sharing my code.

What i am trying to do is i am reading all the json files from user input and looping them and storing it to react state. Then inside ReadFiles() function i am logging the state data. But it is always coming empty data.

I think it calling first and then going to the loop.

I wants to log the datasource data from state inside ReadFiles() function after all Looping operation is done

Is there any way to do that ?

Please have a look

1 Answers1

0

You can make use of instance variable in this case to keep track of whether you are processing last file or not. Once you know that last file is being processed, you can set doNextStep to true in state from callback of last processed file. Then in componentDidUpdate, you can do next step(i.e. console log or anything else).

class Example extends React.Component {
   constructor(props){
    super(props);
    // to keep track of if last file is being processed
    this.lastFile = false;
    
    // doNextStep will tell us that all setState operations are completed or not
    this.state = {
      doNextStep: false,
    }
    }
    
    componentDidUpdate(prevProps, prevState) {
      if(prevState.doNextStep !== this.state.doNextStep && this.state.doNextStep) {
      console.log(this.state.datasource)
      }
    }
    
         
   onReaderLoad = (e) => {
  var obj =JSON.parse(e.target.result)
  this.setState(prevState => ({
    datasource: [...prevState.datasource, obj]
  }), 
  () => if(this.lastFile)) this.setState({doNextStep: true}))
  }
    
  ReadFiles = () => {
    let files = this.state.json_files;

    for (i=0; i<files.length; i++){
      if(i == files.length - 1) this.lastFile = true
      else this.lastFile = false
      
      var reader = new FileReader();
      reader.onload = this.onReaderLoad;
      reader.readAsText(i);
      
    }
  }
        }
mukesh210
  • 2,792
  • 2
  • 19
  • 41