Home > Blockchain >  Call Second API If Condition is Met in React
Call Second API If Condition is Met in React

Time:05-16

I need to call http://sample-api-2.com if callAPI2 is true. Also I need to pass the response?.data.code from http://sample-api-1.com.

What would be the correct way to do this?

export const createProduct =
  ({ data = null, callback = () => {}, callAPI2 = true }) =>
  async (dispatch) => {
    try {
      dispatch({
        type: constants.CREATE_PRODUCT_REQUEST,
      });

      const [response] = await Promise.all([
        axios.post("http://sample-api-1.com", data),
        callAPI2 &&
          axios.post("http://sample-api-2.com", {
            productCode: response?.data.code,
          }),
      ]);

      const product = {
        productCode: response?.data?.code,
        productName: response?.data?.name || null,
      };

      dispatch({
        type: constants.CREATE_PRODUCT_SUCCESS,
        payload: product,
      });

      callback("success");
    } catch (error) {
      dispatch({
        type: constants.CREATE_PRODUCT_FAILURE,
      });

      callback("error");
    }
  };

CodePudding user response:

Assuming you don't need the response from the second API call (you don't show that you use it), you can refactor it this way:

// ...
try {
  dispatch({
    type: constants.CREATE_PRODUCT_REQUEST,
  });

  const response = await axios.post("http://sample-api-1.com", data);
  const productCode = response?.data?.code;
  if (!productCode) throw new Error('Product code not found');
  if (callAPI2) await axios.post("http://sample-api-2.com", {productCode});

  const product = {
    productCode,
    productName: response?.data?.name || null,
  };

  dispatch({
    type: constants.CREATE_PRODUCT_SUCCESS,
    payload: product,
  });

  callback("success");
}
// ...
  • Related