0

I'm trying to add information to the document of the user currently logged in.

I have the following code snippet of code in my component -

console.log("user", auth.currentUser?.uid);

  useEffect(() => {
    if (productId) {
      db.collection("users")
        .doc(auth.currentUser?.uid)
        .collection("cart")
        .doc(productId)
        .onSnapshot((snapshot) => setProduct(snapshot.data()));
    }
  }, []);

Here,

const auth = firebase.auth();

The console log actually gives me the uid of the user but the hook below produces an errror -

FirebaseError: Function CollectionReference.doc() requires its first argument to be of type non-empty string, but it was: undefined

I have used the same approach in another component to add data and it works fine.

Why does this happen? Thanks in advance.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
vaibhav deep
  • 655
  • 1
  • 8
  • 27

1 Answers1

2

auth.currentUser is going to be null if there is no user signed in at the moment it was accessed. Your code is blindly ignoring this possibility by using the ? operator to "safely" access its properties anyway. When you use ?, if the prior expression is "falsy", the entire expression becomes undefined. Your code should instead check for null before assuming there is an object to use.

const currentUser = auth.currentUser
if (currentUser) {
    const uid = currentUser.uid;
}
else {
    // what do you want to do if there is no one signed in?
}

If you need to wait until a user is actually signed in, you should use an auth state observer to get a callback that tells you when the user object is available.

See also: Typescript the safe navigation operator ( ?. ) or (!.) and null property paths

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441