axios get - multiple api calls with response from first api to subsequent calls

走远了吗. 提交于 2019-12-24 06:30:04

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/47030454/axios-get-multiple-api-calls-with-response-from-first-api-to-subsequent-calls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!