Hi, I want to do a request to an API in the componentWillMount method, but I want to know if is correct change the life cycle methods to async to use the await.
Hi Rodrigo,
It is not a best practice to use ComponentWillMount for most things, let alone API calls. If you are passing stuff as props and need to use it in your component, use your constructor to initialise stuff. With respect to API calls, it is highly recommend that you use ComponentDidMount and do something like this:
componentDidMount() {
this.makeRemoteRequest();
}
async makeRemoteRequest() {
try {
let res1 = await this.apiCall1();
let res2 = await this.apiCall2(res1); //You could pass results as params to consecutive functions like this :)
.
.
.
} catch(e) {
console.warn(e);
}
}
Cheers 🙂
Filipe Picoito
Full Stack Developer
Hello,
No it is not.
componentWillMountmight be called multiple times (since react fiber) and it is not the best place to hold JavaScript's Call Stack specially.The place best life cycle method to place calls is within
componentDidMountas it is only called once in the life cycle of the component.Refer to: medium.com/@baphemot/understanding-reactjs-compon…