1

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 />
         </>
      )
    };

};
John Fu
  • 35
  • 5
  • What you return in the promise catch will be the resolved value of the promise and now your promise will never fail even though the request made failed: `const exRateTrendData = await api.exchangeRate.getTrend().catch(error=>failedValueForexRateTrendData)` – HMR Nov 03 '20 at 07:34

1 Answers1

1

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:

async componentDidMount() {
  const date = moment()
    .subtract(1, "month")
    .format("YYYY-MM-DD")

  try {
    const exRateTrendData = await api.exchangeRate.getTrend()

    this.setState({
      dataTrend: exRateTrendData,
    })
  } catch (e) {
    console.log("something wrong with exRateTrendData call")
  }

  try {
    const exRateData = await api.exchangeRate.get(date)
    this.setState({
      dataCurrency: exRateData,
    })
  } catch (e) {
    console.log("something wrong with exRateData call")
  }
}

Tooschee
  • 681
  • 6
  • 11