Skip to content
Advertisement

Reactjs: Best approach to avoid 1 API failure affects other API calls for multiple API calls inside react componentDidMount

I’m writing a react component which requires TWO or MORE API calls inside componentDidMount as below.

The 2 API calls will update 2 different states and thus two different child components will be re-rendered.

However, I believe what I wrote is not the best approach, since potential failure of one API will make another API to fail as well. Beacuse they are put inside componentDidMount together.

I would like to ask what is the best approach to deal with this situation? To avoid 1 API failure affects other API calls for multiple API calls inside componentDidMount? Thx for your kind help!

JavaScript

Advertisement

Answer

Best practice when using async/await is to wrap your code in try{}catch(){} (you can read more about it here), thanks to that you can separate both calls from each other in componentDidMount, so they can fail separately:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement