-1

I am having this weird issue and I could not figure it out.

I have a button which I click and a file window would appear

When the user selects a file and click OK, I have this.setState({file}) to record the file that the user has selected. But it does not work.

<div id="file-upload-submit-btn-container">
     <Button id="choose-file-btn" 
           onClick={this.buttonClick.bind(this)}>
            Choose file
     </Button>
     <input type="file" id="upload-input" 
            onChange={this.handleInputSelect.bind(this)} 
            onClick={(e) => e.target.value = null}  // reset input file
            multiple={false}/>
</div>

javascript

constructor() {
    super()
    this.state ={
        url: "https://example.com:8303",
    }
}


getFileUploader() {
    return $(this.refs.dropzone).find("#upload-input") 
}

buttonClick(e) {
    e.preventDefault()
    let $fileuploader = this.getFileUploader()
    $fileuploader.trigger('click');
}

handleInputSelect(e) {
    e.preventDefault()
    let file = e.target.files[0]
    this.setState({file})      <---- setState at here, but it is not getting recorded
    console.log(file, this.state.file)  <---file IS defined here but not this.state.file, why?

    this.handleUpload()
}
齐天大圣
  • 1,169
  • 5
  • 15
  • 36

2 Answers2

2

From React.js documentation:

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

Bill
  • 4,506
  • 2
  • 18
  • 29
0

If you want to access the file just after state is set,

You should use it like :

this.setState({file} , () => {
    console.log(file, this.state.file)
});

And why you are not accessing it right after state is set, is explained by @quidproquo.

Think of setState() as a request rather than an immediate command to update the component. For better perceived performance, React may delay it, and then update several components in a single pass. React does not guarantee that the state changes are applied immediately.

Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122