1

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?

Marco Marioni
  • 23
  • 1
  • 6
  • inside the method, that gets executed with a submit/click, would update the state of a `loading` variable to true. Then in render (return), woudl do a simple check `this.state.loading ? //the loading button : //base button`. and after the axios done its post/fetch - make it execute another set state that sets `loading` to `false`. Wouldint use `await` because that could be causing issues. Another way would be set the state of `loading` to `true`, then using `useEffect` on `loading` change execute the axios. and axios, once done its job, changes `loading` to `false`. few ways i can think of – Lith Apr 19 '21 at 19:34
  • Does this answer your question? [Using async setState](https://stackoverflow.com/questions/43370176/using-async-setstate) – Janez Kuhar Apr 19 '21 at 21:42

1 Answers1

2

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.

alisasani
  • 2,808
  • 1
  • 7
  • 15