Home > Software design >  React custom hook to fetch document from firebase isLoading always false
React custom hook to fetch document from firebase isLoading always false

Time:11-15

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?

CodePudding user response:

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

CodePudding user response:

From w3schools.com:

The try statement defines the code block to run (to try).

The catch statement defines a code block to handle any error.

The finally statement defines a code block to run regardless of the result.

So you're setting it to true in the try then setting it back to false right after.

  • Related