如果在 React 中满足条件,则调用第二个 API

Call Second API If Condition is Met in React

如果 callAPI2 为真,我需要调用 http://sample-api-2.com。 我还需要从 http://sample-api-1.com.

传递 response?.data.code

执行此操作的正确方法是什么?

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

假设您不需要第二次 API 调用的响应(您没有表明您使用它),您可以这样重构它:

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