Initially I am rendering Upload file
text with a button.After clicking this it is calling _handleSubmit
which sends file to an API.
After this sending is done I want to change Upload file
to Upload done
.For that I have created a variable isSend
but not able to use it.
_handleSubmit(e) {
e.preventDefault();
const fl = new FormData();
fl.append("name", this.state.file);
const req = request
.post("/upload")
.send(fl);
req.end(function (err, response) {
if (response=== "OK") {
this.setState({//not setting showing error
isSend: true
});
}
});
}
render() {
const isSend = this.state.isSend; //false initially
return (
<div>
<h3>Upload file</h3> //Show done upload after done
<button
type="submit"
onClick={(e) => this._handleSubmit(e)}>Upload File
</button>
</div>
)
}
You forgot to bind
the context
, Use this:
req.end((err, response) => {
if (response=== "OK") {
this.setState({ //it will work
isSend: true
});
}
});
or use .bind(this)
with callback method, like this:
req.end( function(err, response) {
if (response=== "OK") {
this.setState({ //it will work
isSend: true
});
}
}.bind(this));
And check the value of isSend
inside render method to change the text, like this:
render() {
const isSend = this.state.isSend; //false initially
return (
<div>
<h3> {isSend ? 'Upload Done' : 'Upload file' } </h3>
<button
type="submit"
onClick={(e) => this._handleSubmit(e)}>Upload File
</button>
</div>
)
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments