简体   繁体   English

我正在尝试通过反应从 Api 获取数据,一个 api 取决于第二个的“id”,

[英]I am trying to fetch data from Api with react, one api depends on "id" the second's one,

here is my code, first fetch return good data but second fetch brings only promise这是我的代码,第一次获取返回良好的数据,但第二次获取只带来承诺

    const data = await axios.get(
      `${API_URL}/${id}`
    );
    return data.data;
  };
  const fetchData = async () => {
    setLoading(true);
    const res = await axios.get("${API_URL}");
    setData(
        res.data.map(el => {
          const fromApi = fetchIncomes(el.id);
          return {
            ...el,
            ...fromApi
          };
        })
      )
    setLoading(false);
  };

You need to await the promises returned by fetchIncomes .您需要等待fetchIncomes返回的承诺。

Try this:试试这个:

const fetchIncomes = async (id) => {
  const data = await axios.get(`${API_URL}/${id}`);
  return data.data;
};

const fetchData = async () => {
  setLoading(true);

  const res = await axios.get("${API_URL}");

  // Create array of promises
  const promises = res.data.map(el => {
    return fetchIncomes(el.id)
      .then(fromApi => {
        return {
          ...el,
          ...fromApi
        };
      });
  });

  // Await all promises to resolve
  const newData = await Promise.all(promises);

  // Update state with new data
  setData(newData);
  setLoading(false);
};

Note: If you want, you could also use async-await for your array of promises:注意:如果你愿意,你也可以为你的承诺数组使用 async-await :

const promises = res.data.map(async (el) => {
  const fromApi = await fetchIncomes(el.id);
  return {
    ...el,
    ...fromApi
  };
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我正在尝试从Rest API中获取json数据以进行反应,但是它显示了一些错误 - I am trying to fetch json data from Rest API into react, but it showing some error 如何在 React 的一个组件中获取 2 个 api - How to fetch 2 api's in one component in React 我正在尝试使用 useContext 将 api 数据从一个组件访问到另一个组件,但我没有这样做 - I am trying to use useContext to give access of the api data from one component to other but i am failing to do so 当我尝试从节点 js 获取 api 时,它不起作用 - When i am trying fetch api from node js it is not working 当我尝试通过在反应中使用 useEffect 从 API 获取数据时遇到问题 - I'm fetching a problem when I'm trying to fetch data from an API by using useEffect in react 尝试从api获取数据时变得不确定-React - Getting undefined when trying to fetch data from an api - React React,如何通过选择起点ID从api中获取数据 - React, how to fetch data from an api by selecting the startpoint ID 反应:根据 id 从 rest api 获取数据 - react: fetch data from rest api according to id 尝试使用早期api提取中的ID进行api提取 - Trying to do an api fetch using id from earlier api fetch 使用多个 React 钩子 useEffect 从 API 中获取数据,当第二次获取时使用第一个钩子中的数据 - Fetch data from API with multiple React hook useEffect when second fetch use data from first hook
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM