Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React custom hook to fetch document from firebase isLoading always false

I created this custom hook to fetch (in this case listen to) a document in firestore:

import { doc, onSnapshot } from 'firebase/firestore';
import { useEffect, useState } from 'react';
import { db, auth } from '../../firebase';

function useCurrentUser() {
  const userId = auth.currentUser.uid;

  const [user, setUser] = useState({});
  const [isUserLoading, setIsUserLoading] = useState(false);
  const [isUserError, setIsUserError] = useState(null);

  useEffect(() => {
    const getUser = async () => {
      try {
        setIsUserLoading(true);
        const userRef = doc(db, 'users', userId);
        const unsub = await onSnapshot(userRef, doc => {
          setUser(doc.data());
        });
      } catch (error) {
        setIsUserError(error);
      } finally {
        setIsUserLoading(false);
      }
    };

    getUser();
  }, []);

  return { user, isUserLoading, isUserError };
}

export default useCurrentUser;

The problem is: isUserLoading is always returning false even though in the try statement, I’m setting it to true

Any idea why this is happening?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

onSnapshot returns a function, not a promise, so you can’t await

So what you want to do is:

useEffect(() => {
  setIsUserLoading(true);
  const userRef = doc(db, 'users', userId);
  const unsub = onSnapshot(userRef, snapshot => {
    if(!snapshot.exists()) return
    setIsUserLoading(false);
    setUser(snapshot.data());
  });

  return unsub
}, []);

In your current code, finally would run immediately, because there is nothing to await for

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading