How to use useEffect inside map function?

前端 未结 2 1710
囚心锁ツ
囚心锁ツ 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条回答
  • 2021-01-28 00:04

    Just to highlight how you can use isClaimed as hoook and set state calling a async function inside it. Later use the above hook in a react component. Please follow below sanbox.

    https://codesandbox.io/s/confident-cray-4g2md?file=/src/App.js

    0 讨论(0)
  • 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?
    0 讨论(0)
提交回复
热议问题