Reputation: 23
I'm coding a React app and I encountered a problem.
I want to change the state of a buttonfrom Write to Loading... when I call the HandleApiCall
function and I want to mantain it until I get all the data from the Axios api call.
I'm using a class component
This the JSX code.
<form onSubmit={this.HandleApiCall.bind(this)}>
<div className="TextAreaContainer">
{ this.state.loading === false ?
<button className= "btn_" type="submit" >Write</button> :
<button className= "btn_" type="submit">Loading...</button>
}
</div>
<div className="TextareaContainer">
<textarea
className= "textarea"
placeholder="write the description here"
value={this.state.input}
onChange={(ev) => {
this.updateBody(ev.target.value)
}
}>
</textarea>
</div>
</form>
This is the HandleApiCall funtion
HandleApiCall(e) {
e.preventDefault();
await this.setState({ loading : true });
axios.post(TRANSLATE_API_URL, body).then(({ data: { text } }) => {//some code here});
}
I tried to do in that way but it does not work.
Any ideas?
Upvotes: 1
Views: 824
Reputation: 2968
Firstly, you should change the value of loading to false after calling the API:
async HandleApiCall(e) {
e.preventDefault();
this.setState({ loading : true });
await axios.post(TRANSLATE_API_URL, body).then(({ data: { text } }) => {//some code here});
}
this.setState({ loading : false });
Then, you only need to create one butto element and change its text according to the value of loading
<button className= "btn_" type="submit" >{loading ? "Loading" : "Write"}</button>
Besides, you don't need to use await
for the setState
as it doesn't return a promise.
Upvotes: 2