Skip to content
Advertisement

How can I check if a firebase Reference is empty before fetching it?

I’m trying to fetch a specific document from firebase. If it exists, great. But if it doesn’t, I don’t want it to break my app. I just want it to move on. However, I can’t seem to shake off this error:

my error

Here is my code:

async function getOtherInfo() {
        //get profile image, username if they exist
    
        const profileRef = doc(db, "profiles", email);
       
        const snap = await getDoc(profileRef);
        if (snap.exists()) {
          setProfileImg(snap.data().profileImg);
          setUserName(snap.data().userName);
        }

Firebase gurus, please help me, I’m going crazy soon. Thanks a bunch.

edit: added code sections to show where my db and email state is coming from. Both are valid.

//init services
const db = getFirestore();

const [email, setEmail] = useState(identifier.email)

Advertisement

Answer

If think you’r looking for:

if (email) { // 👈
    //get profile image, username if they exist

    const profileRef = doc(db, "profiles", email);
   
    const snap = await getDoc(profileRef);
    if (snap.exists()) {
      setProfileImg(snap.data().profileImg);
      setUserName(snap.data().userName);
    }

This ensure that you only try to load the document if there actually is an email value.

Advertisement