I have a small React App in which I read the email and file from the user and send it to back end api. (I want the user to upload just one file not multiple)
class App extends Component{
constructor(props){
super(props);
this.state={
email:"",
file:null
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleFile = this.handleFile.bind(this);
}
handleChange=(event) => {
this.setState({
email: event.target.value
})
console.log(this.state)
}
handleFile=(event) => {
this.setState({
file: event.target.files[0]
})
}
handleSubmit= (event) =>{
const data = new FormData();
data.append('file', this.state.file);
data.append('email', this.state.email);
axios.post('/files', data).then((response) => {
console.log(response);
})
console.log(data); //returns null
console.log("form submit")
console.log(this.state)
}
render(){
return(
<div>
<form>
<label> Email : </label>
<input name="email" type="text" onChange = {this.handleChange}/>
<label> Upload File : </label>
<input name="file" type="file" onChange={this.handleFile}/>
<button type="submit" onClick={this.handleSubmit}>Submit</button>
</form>
</div>
);
}
}
export default App;
The issue I'm facing is that the formData returns null. So, when I print the data
it gives me null values but I can see that the state values are being updated. Why is that happening?