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!
import React from "react";
import * as api from "api";
import moment from "moment";
class ExchangeRate extends React.Component {
constructor(props) {
super(props);
this.state = {
dataCurrency: [],
dataTrend: []
}
};
async componentDidMount() {
const date = moment().subtract(1, "month").format("YYYY-MM-DD");
const exRateTrendData = await api.exchangeRate.getTrend();
const exRateData = await api.exchangeRate.get(date);
this.setState({
dataCurrency: exRateData,
dataTrend: exRateTrendData,
});
};
render() {
return (
<>
<Component1 depending on dataCurrency />
<Component2 depending on dataTrend />
</>
)
};
};