skip to Main Content

I am creating a react project where I want to grab the users name from my firestore database and I encountered an error while querying. I found when comparing the 2 strings passed to the function and taken from the data base it is returing false when the strings are the same.

const fetchUserName = async (userid: string) => {
  try {
    const userdb = collection(firestore, "users");
    const querySnapshot = await getDocs(userdb);
    const userDoc = querySnapshot.docs[1].data().uID;
    console.log(userDoc, userid);
    console.log(userDoc === userid);
    console.log(typeof userDoc, typeof userid);
    return userDoc;
  } catch (error) {
    console.error("Error fetching user name:", error);
  }
};

the output of the first console.log is ZZ7KDH1U2lenkHI331ryrxOECUg2 "ZZ7KDH1U2lenkHI331ryrxOECUg2", the second one is false, and the third is string string. I don’t understand why its not working and cant seem to find any answers online.

2

Answers


  1. There might be hidden characters or extra whitespace causing the string comparison to fail. Try using .trim() on both userDoc and userid:

    console.log(userDoc.trim() === userid.trim());

    Also, check if there are any hidden characters by comparing the lengths of both strings:

    console.log(userDoc.length, userid.length);

    These steps should help identify and fix the issue with the string comparison.

    Login or Signup to reply.
  2. It might be due to the fact on how uid is being treated in the backend, try converting the uid to string so const userDoc = String(querySnapshot.docs[1].data().uid) I have had previous experience with this type of error sometimes this was the cause

    Let me know if this works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search