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!

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

};

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:

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")
  }
}

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