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
onSnapshot
returns a function, not a promise, so you can’tawait
So what you want to do is:
In your current code,
finally
would run immediately, because there is nothing to await forFrom w3schools.com:
So you’re setting it to
true
in thetry
then setting it back tofalse
right after.