0

I'm iterating through a collection in an event handler and run the function setInStateAsBase64 on each item to convert it and set it to state.

When the iteration is done I want to get all items set to state, so I can upload them. But I can't (despite them being successfully set to state), because of some asynchronicity going on.

In what way should I restructure the code in this React context to get hold hold of these values (to be able to upload them).

setInStateAsBase64(file) {
  var self = this;
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function () {
    const newTempFiles = [...self.state.tempFiles, reader.result];
    self.setState({
      tempFiles: newTempFiles
    });
  };
}

handleDrop(acceptedFiles, rejected) {
  acceptedFiles.map((file) => {
    this.setInStateAsBase64(file)
  })
  console.log(22, this.state.tempFiles.length)
  // returns 0 items
}
Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • What's the problem exactly? That you're getting `0` from your `console.log`? If so, of course you are, it's running before the reader has done its thing. – T.J. Crowder May 15 '17 at 10:20
  • Sorry for not being clearer about the problem, I will edit the question. But how hasn't the reader done it's thing when it's run before my console output? – Fellow Stranger May 15 '17 at 10:22
  • The exact problem is not very clear from the question. Try rewording it and add the expected and the current result. – hazardous May 15 '17 at 10:22
  • @FellowStranger: Because it's *asynchronous*. `setInStateAsBase64` *starts* the read, but the read finishes *after* it (and `handleDrop`) have both returned. Other than the `console.log`, you're handling that correctly. – T.J. Crowder May 15 '17 at 10:23
  • So the answer is that this isn't possible. (I've now fruitlellsly tried solutions provided in the linked question, using Filereader in React should be avoided.) – Fellow Stranger May 15 '17 at 11:09

0 Answers0