In my experience over the past few months, I've realized that the best way to achieve this is:
class App extends React.Component{
constructor(){
super();
this.state = {
serverResponse: ''
}
}
componentDidMount(){
this.getData();
}
async getData(){
const res = await axios.get('url-to-get-the-data');
const { data } = await res;
this.setState({serverResponse: data})
}
render(){
return(
<div>
{this.state.serverResponse}
</div>
);
}
}
If you are trying to make post request on events such as click, then call getData()
function on the event and replace the content of it like so:
async getData(username, password){
const res = await axios.post('url-to-post-the-data', {
username,
password
});
...
}
Furthermore, if you are making any request when the component is about to load then simply replace async getData()
with async componentDidMount()
and change the render function like so:
render(){
return (
<div>{this.state.serverResponse}</div>
)
}