skip to Main Content

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?

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search