[英]How can I fetch data with an array in react?
I am trying to get all data of the applicants in an array:我正在尝试以数组形式获取申请人的所有数据:
Here is following code that how I fetch an array:以下是我如何获取数组的代码:
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);
};
after I console.log(applicants)
在我
console.log(applicants)
之后
it gave me this:它给了我这个:
[{…}]
0:
applicant_publicId: "La1618912810062"
application_letter: "apply"
id: 3
response: "Waiting on review"
Now im trying to fetch data again with the applicant_publicId
to get more data:现在我尝试使用
applicant_publicId
publicId 再次获取数据以获取更多数据:
/api/v1/profiles/profile/${index.applicant_publicId}
How can I do that?我怎样才能做到这一点?
You can't await
inside the .map
callback as it is synchronous, but you can map the response data to an array of requests for the profiles and use Promise.all
and wait for them all to resolve to an array of profiles.您不能在
.map
回调中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);
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.