[英]How do I get data from the async/await function before rendering out the UI?
I am working out on Github API and using an async/await function to get a list of user's repository.我正在研究 Github API 并使用异步/等待 function 来获取用户存储库的列表。
The problem I am facing is, I am using a Dropdown component
where I have to provide an array full of repo list which will work as a dropdown, and that array data is coming from the async/await function.我面临的问题是,我正在使用一个
Dropdown component
,我必须在其中提供一个充满 repo 列表的数组,该数组将作为下拉列表工作,并且该数组数据来自 async/await function。
const list = []
async function fetchRepos() {
await octokit.repos
.listForUser({
username: 'abhinav-anshul',
})
.then((details) => list.push(details.data[0].name))
console.log('List Array', list)
console.log([...list])
}
Therefore, the UI renders before the function gets executed, and the items array
turns out to empty.因此,UI 在 function 执行之前呈现,并且
items array
变为空。
<>
<DropDown items={[...list]} placeholder='Select a Repository' />
</>
I am using the spread operator
to get data in my Dropdown component
我正在使用
spread operator
在我的Dropdown component
中获取数据
How do I make sure that I do get data in the items prop from the async-await function, I believe the function cannot be synchronous as well since it is handling the API request.我如何确保我确实从异步等待 function 获取项目道具中的数据,我相信 function 也不能同步,因为它正在处理 ZDB974238714CA8ADE634A7CE1D08 请求。 What could be a good strategy for this problem?
什么是解决这个问题的好策略?
Any help is really appreciated.非常感谢任何帮助。
Thank You谢谢你
You could initialise your list data with a falsy value, say null and use a ternary operator to stop the Dropdown UI from rendering until your API call finishes executing and populates your list data with the array.您可以使用虚假值初始化列表数据,例如 null 并使用三元运算符停止下拉 UI 呈现,直到您的 API 调用完成执行并使用数组填充列表数据。 This would be 'truthy' value and then your Dropdown could be rendered.
这将是“真实”值,然后可以呈现您的下拉菜单。
You'll have to use useState
and useEffect
to achieve this if you are using hooks based components.如果您使用基于钩子的组件,则必须使用
useState
和useEffect
来实现此目的。 It will look something like this它看起来像这样
const [list, setList] = useState([]);
async function fetchRepos() {
await octokit.repos
.listForUser({
username: 'abhinav-anshul',
})
.then((details) => {
setList((prevState) => {
prevState.push(details.data[0].name);
return prevState;
});
});
console.log('List Array', list);
console.log([...list]);
}
useEffect(() => {
(async () => {
await fetchRepos();
})();
}, []);
Can try below solution可以试试下面的解决方案
const [isShowDropdown, setDropdown] = useState(false);
const list = []
async function fetchRepos() {
await octokit.repos
.listForUser({
username: 'abhinav-anshul',
})
.then((details) => list.push(details.data[0].name))
setDropdown(true)
console.log('List Array', list)
console.log([...list])
}
Render dropdown like this像这样渲染下拉菜单
<>
{isShowDropdown?<DropDown items={[...list] || [] } placeholder='Select a Repository' />:null}
</>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.