1

I was working on a project and was using firestore database from Firebase. I want to fetch data from the database once the page is reloaded. So the below code is working fine even without async await. But I have studied that we need async/await while API/DATA calls, please help me if I am wrong?

useEffect(() => {
      db.collection('database_mcq').onSnapshot(snapshot => { setMcq(snapshot.docs.map(doc => doc.data())) })
      
  }, [])
Dhruv Kothari
  • 103
  • 2
  • 7
  • 1
    async/await is very specific for asynchronous requests featuring so-called promises. As your code doesn't use promises, you just cannot use async/await in it – devnull69 May 19 '21 at 18:09
  • Does this answer your question? [React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing](https://stackoverflow.com/questions/53332321/react-hook-warnings-for-async-function-in-useeffect-useeffect-function-must-ret) – Kevin B May 19 '21 at 18:11
  • Given the way it is, it isn't – Kevin B May 19 '21 at 18:19

1 Answers1

3

It's not only unnecessary, it's also forbidden - if you try to use an async function, React will throw an error, because the only thing that can be returned from an effect callback should be a function or nothing at all (and not a Promise).

Instead, use .then - if you're using standard Promises - or use whatever other method the API you're using provides for interacting with asynchrony. In your case, onSnapshot is fulfilling that role - there's no need to do anything else special.

Even in standard JavaScript, there's no requirement to ever use async/await, since it's just syntax sugar over .then.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • You can use async/await inside of an effect hook by creating an async function inside the hook and invoking the function just like in the example you linked. – Sean W May 19 '21 at 18:17
  • @SeanW you can, but should you? – Kevin B May 19 '21 at 18:18
  • Depends - if you have a few dependent promises, chaining can be hard to follow in some situations. – Sean W May 19 '21 at 18:29