2

How to make multiple api calls with axios - when I have to pass a value from my first api response to all subsequent calls. I have 2 other calls to be made inside getData function where I have to pass a value from y first api response {data} - how to chain multipl requests with axios? 2 next calls are dependent on first call - they are not dependant on each other - they can happen in parallel - the only issue I have is - I am not able to pass the response data to the subsequent end-points.

import Request from 'axios';

export function getData() {
  return async function getData(dispatch) {
    const { data } = await getDatafromService();
    dispatch({ type: 'Data_fetch', payload: data });
  };
}

async function getDatafromService() {
  const endpoint = "api-url";
  return Request.get(endpoint);
}
hazardous
  • 10,627
  • 2
  • 40
  • 52
monkeyjs
  • 604
  • 2
  • 7
  • 29

1 Answers1

0

Something like this should work for an overall structure.

The async function getData will ultimately return an array of the responses from the last two requests.

import Request from 'axios';

export function getData() {
  return async function getData(dispatch) {
    const { data } = await getDatafromService();
    return Promise.all([
      sendDataToFirstService(data),
      sendDataToSecondService(data),
    ])
  };
}

function getDatafromService() {
  const endpoint = "api-url";
  return Request.get(endpoint);
}

function sendDataToFirstService(data) {
  const endpont =  "first-url";
  return Request.post(endpoint, data)
}

function sendDataToSecondService(data) {
  const endpont =  "second-url";
  return Request.post(endpoint, data)
}

Note that you may need to modify the data received from the original get request before passing it to the next two.

You can do this by chaining .then onto the Promise like so...

function getDatafromService() {
  const endpoint = "api-url";
  return Request.get(endpoint).then(({data}) => modify(data));
}
Marc Davies
  • 256
  • 1
  • 8