Home > database >  Multiple API calling one after another in Axios in React
Multiple API calling one after another in Axios in React

Time:06-29

I need to call http://sample.com multiple times depending on the number of data. After that I also need to call http://sample2.com multiple times after calling http://sample.com since the response from http://sample.com is need to be pass to http://sample2.com.

I need to know how can I make them all finished before calling the success dispatch properly?

export const createAllProducts =
  ({ data = null, isCall2 = false }) =>
  async (dispatch) => {
    try {
      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_REQUEST,
      });

      const requests = data.map(({ test, name }) => {
        return getAxiosService().post("http://sample.com", {
          test,
          name,
        });
      });

      const responses = await Promise.all(requests);


      const productCode = responses?.map(({ code }, index) => {
        if (!productCode) throw new Error("Code not found");
        if (isCall2)
          await getAxiosService().post("http://sample2.com", {
            code,
          })
      });
      

      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_SUCCESS,
      });
    } catch (error) {
      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_FAILURE,
      });
    }
  };

CodePudding user response:

To run the API calls in parallel and wait for all those to complete, you need change the code to following

if (isCall2 && responses) { 
     await Promise.all(responses.map(async ({ code }, index) => {          
        await getAxiosService().post("http://sample2.com", {
            code,
        });
     }));
}

Full code:

export const createAllProducts =
  ({ data = null, isCall2 = false }) =>
   async (dispatch) => {
    try {
      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_REQUEST,
      });

      const requests = data.map(({ test, name }) => {
        return getAxiosService().post("http://sample.com", {
          test,
          name,
        });
      });

      const responses = await Promise.all(requests);

      if (isCall2 && responses) { 
        await Promise.all(responses.map(async ({ code }, index) =>{          
          await getAxiosService().post("http://sample2.com", {
            code,
          });
        }));
    }
      
    dispatch({
        type: constants.CREATE_ALL_PRODUCTS_SUCCESS,
      });
    } catch (error) {
      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_FAILURE,
      });
    }
  };
  • Related