How to use useEffect inside map function?

前端 未结 2 1729
囚心锁ツ
囚心锁ツ 2021-01-27 23:15

I have two tables in Firebase: Vouchers & ClaimedVouchers. I am trying to display the vouchers that do not appear in the ClaimedVouchers table. So, I have a query that gets

2条回答
  •  Happy的楠姐
    2021-01-28 00:10

    Your isClaimed is an async function, meaning that it returns a promise - or a delayed result. If you want to wait for the result when calling isClaimed, you'll need to use await:

    await isClaimed(voucher.voucherID, uid);
    console.log(result);
    

    This most likely isn't possible in a render method though, which is why (as Asutosh commented) you'll have to store the result in the state, and then use the state in your render method.

    So the setup you need is:

    • Start the loading of all your data in componentDidMount or with useEffect.
    • When the data is loaded, put it in the state with setState or a state hook.
    • Use the data in your render method.

    For a few examples of this, see:

    • Firebase switch header option with onAuthStateChanged
    • React + Firestore : Return a variable from a query
    • How to render async data in react + firestore?

提交回复
热议问题