Home > Enterprise >  Get the var value out of IF statement
Get the var value out of IF statement

Time:10-05

I'm trying to do a comparison between user session email and an email in an array in firestore. That is, I want to search for the login email within the database and if any email is found, bring some information to the screen, such as name and surname.

I even managed to get inside the array and make this comparison, but I can't make the "var UserName" leave the { } of the IF

Can someone help me?

my code is:

    const [data, setData] = useState([]);
    const getUsers = () => {
      firestore()
      .collection("users")
      .get()
      .then((querySnapshot) => {
        let userFirestore = [];
        querySnapshot.forEach((doc) => {
            
            const usuario = {
              id: doc.id,
              nome: doc.data().nome,
              sobrenome: doc.data().sobrenome,
              email: doc.data().email,
              profissao: doc.data().profissao,
            }
            userFirestore.push(usuario);

        });
        
        userFirestore.forEach(function (item, indice, array) {
          if (item.email === user.email){ //user.email brings the email of the logged in user
            var nomeUsuario = item.nome
            console.log(nomeUsuario) //UserName brings the result I expected
          } 

        });
    })
    .catch((error) => console.log(error));
    }

CodePudding user response:

You can use a query to get a document with current user's email that instead of fetching the whole collection as shown below:

firestore()
  .collection("users")
  .where("email", "==", user.email)
  .get().then((querySnapshot) => {
    if (querySnapshot.empty) {
      console.log("User not found")
      return;
    } 
      
    const user = querySnapshot.docs[0].data();
    console.log(user)
  })

Even better, if you use user's UID as the Firestore document ID (highly recommended), then you can get that single document by ID as shown below:

firestore()
  .collection("users")
  .doc(user.uid) // < user.uid must be defined
  .get()
  .then((snapshot) => {
    console.log(snapshot.data())
  })

When you fetch the whole collection, you are charged N read where N is total number of documents in the collection and it'll be slower as you are downloading plenty of data.

  • Related