简体   繁体   English

在渲染 UI 之前,如何从 async/await function 获取数据?

[英]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.如果您使用基于钩子的组件,则必须使用useStateuseEffect来实现此目的。 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.

相关问题 如何从该异步等待 function 中成功从数据库中获取数据的 output 样式? - How do I style the output from this async await function that successfully fetches data from a database? 如何在没有async / await的情况下从待解决的承诺中获取数据? - How do I get data from pending resolved promise without async/await? 如何修复此异步/等待 function? - How do I fix this async/await function? 我需要在异步函数中的每个语句之前放置 await 吗? - Do I need to put await before every statement in an async function? 异步/等待,如何强制我的函数等待,直到诺言被解决,然后才能继续? - Async / Await, how do I force my function to wait until promise is resolved before it continues? 无法从等待/异步功能获取数据 - can't get data from await/async function 如何等待 setTimeout function 中的代码,直到我得到另一个异步 function 的响应 - how to await the code in the setTimeout function till I get the response from an another async function 处理我从异步 function 中得到的数据 - Work with data that I get out of an async function 如何正确等待javascript中异步函数的返回? - How do I correctly await the return of an async function in javascript? 如何在这个 function 中使用 await 和 async? - How do I make use of await and async in this function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM