Search code examples
javascriptreactjsfirebaseformikyup

Reactjs variable not defined error when declared inside conditional statement


I am defining my const/var in a if condition and using it but it still says that its not defined. the var/const is userfinal:

const uploadPostOnline = async (imageUrl, caption) => {
  const userId = auth.currentUser.uid;
  console.log(userId);
  const collectionRef = collection(db, "posts");

  const querySnapshot = await getDocs(collection(db, "realusers"));
  querySnapshot.forEach((doc) => {
    if (doc.data().owner_uid === userId) {
      var userfinal = doc.data().username;
      console.log(doc.data().username);

    }

  });

  addDoc(collectionRef, {
    imageUrl,
    caption,
    username: userfinal,(NOTE: it says userfinal is not defined)
    likes: 0,
    likesByUsers: [],
    comments: [],
    createdAt: serverTimestamp()
  });
};

Solution

  • This should work:

    let userfinal; // 👈
    const querySnapshot = await getDocs(collection(db, "realusers"));
    querySnapshot.forEach((doc) => {
      if (doc.data().owner_uid === userId) {
        userfinal = doc.data().username; // 👈
      }
    });
    
    addDoc(collectionRef, {
      imageUrl,
      caption,
      username: userfinal,
      likes: 0,
      likesByUsers: [],
      comments: [],
      createdAt: serverTimestamp()
    });
    

    The way you're selecting the user is very inefficient though. You're loading all document from realusers to find only one it seems. That's going to cost you more money as you have more users in realusers, and is going to be eating up the bandwidth of your users too.

    It's better to use a query to only request the user(s) you need from the database. Something like:

    const qry = query(collection(db, "realusers"), where("owner_uid", "==", userId));
    
    const querySnapshot = await getDocs(qry);