1

This is a file upload handler I have in my code.

onFileUpload() {
    const file = document.querySelector('input[type=file]').files[0];

    const reader = new FileReader();    
    console.log('contents of file:', reader.readAsText(file));

    this.props.getFile(file); // an action
  }

This code snippet logs undefined to the console. What does it lack?

UPDATE 1. The render() method in the React component. The onFileUpload() method was binded in the constructor with this.onFileUpload = this.onFileUpload.bind(this).

render() {
    return (
      <div>
        ...
        <input type='file' id='files' className='file-input-hidden' onChange={this.onFileUpload} />
      </div>
    );
  }
El Anonimo
  • 1,759
  • 3
  • 24
  • 38

1 Answers1

2
onFileUpload() {
    const file = document.querySelector('input[type=file]').files[0];

    const reader = new FileReader()
    reader.onload = event => console.log(event.target.result)
    reader.onerror = error => throw(error)
    reader.readAsText(file)

    this.props.getFile(file); // an action
  }

You just have to add a listener to do the logging rather than doing it synchronously

Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25