Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the var value out of IF statement

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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));
    }

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading