我正在尝试以数组形式获取申请人的所有数据:
这是我如何获取数组的以下代码:
const [applicants, setTeamApplications] = useState([]);
const fetchApplicationData = async () => {
const res = await axios.get(`/api/v1/invites/team/applications/${teamId}`);
const items = res.data.map((item) =>
await axios.get(`/api/v1/profiles/profile/${item.applicant_publicId}`)
);
// Set state
setTeamApplications(res.data);
// Toggle loading state
setLoadingState(false);
};
在我console.log(applicants)
之后
它给了我这个:
[{…}]
0:
applicant_publicId: "La1618912810062"
application_letter: "apply"
id: 3
response: "Waiting on review"
现在我尝试使用 applicant_publicId
再次获取数据以获取更多数据:
/api/v1/profiles/profile/${index.applicant_publicId}
我该怎么做?
答案 0 :(得分:1)
您不能在 await
回调中使用 .map
,因为它是同步的,但您可以将响应数据映射到配置文件的请求数组并使用 Promise.all
并等待它们全部解析为一系列配置文件。
const [applicants, setTeamApplications] = useState([]);
const fetchApplicationData = async () => {
// Toggle loading state
setLoadingState(true);
try {
const res = await axios.get(`/api/v1/invites/team/applications/${teamId}`);
const profileReqs = res.data.map((item) =>
axios.get(`/api/v1/profiles/profile/${item.applicant_publicId}`)
);
const items = await Promise.all(profileReqs);
// Set state
setTeamApplications(res.data);
setProfiles(items);
} catch (error) {
// handler any error state?
} finally {
// Toggle loading state
setLoadingState(false);
}
};