[英]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.