0

I have the following React component below. The code is successful in sending my file to the back-end as desired. However, I would like to set set the state back to null after the submit button is clicked. What would be the best way to do so here?

state = {
  selectedFile: null
}

handleInputChange = event => {
  this.setState({
    selectedFile: event.target.files[0]
  })
}

fileUpload = () => {
  var fd = new FormData();
  fd.append('form', this.state.selectedFile, this.state.selectedFile.name);
  fetch('/upload', {method: 'POST', credentials: 'include', body: fd})
  .then(res => {
    console.log(res);
  })
  this.setState({ selectedFile: Null })
}


render() {return (
  <Form>
      <h2>Request Form Upload</h2>
      <Form>
      <Form.Input label="Attach a file" name='Form' type="file" onChange={this.handleInputChange} autoFocus />

      <Form.Button onClick={this.fileUpload}>Upload</Form.Button>
      </Form>
  </Form>

 )}
}
Hysii
  • 473
  • 6
  • 16
  • Have you tried `this.setState({ selectedFile: null });` after your axios request is done? – Tholle Jul 17 '18 at 20:17
  • Yes i tried, and get an error saying that my state is null when trying to post with axios – Hysii Jul 17 '18 at 21:00
  • Could you include your entire `fileUpload` function? It's hard to say without seeing all the code. – Tholle Jul 17 '18 at 21:01
  • @Tholle edited with the your recommended change. If you need to see the axios data, i can share that too – Hysii Jul 17 '18 at 21:06
  • Yes, include the entire function please. Try and write `null`, not `Null` with a capital `N`. – Tholle Jul 17 '18 at 21:07
  • @Tholle wasnt using axios, using fetch actually....regardless, code above – Hysii Jul 17 '18 at 21:38
  • You might want to put a `ref` on the `Form.Input` and [use this technique](https://stackoverflow.com/questions/20549241/how-to-reset-input-type-file/20552042). – Tholle Jul 17 '18 at 21:41

0 Answers0