1
votes

I want to send a verification email after user sign up. I wrote that code but if i want to get the current user with firebase on react native it always return null. How can i fix it?

Here is the sign up function:

firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(navigation.navigate("WaitingRoom"))
.catch((err) => console.log(err));

And also email verification function in WaitingRoom:

firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      user
        .sendEmailVerification()
        .then(() => {
          console.log(":)");
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      console.log(":(");
    }
  });

I also tried firebase.auth().currentUser but it return null too.

1
What do you mean by "it always return null"?? Does it mean that it never happens, in the onAuthStateChangedobserver that useris not null (i.e. you always see the result of console.log(":("); in the log)?Renaud Tarnec
It happens but there is a delay and sometimes i have to reload page. I think i have to wait for response or something like that. But i did not find it. @RenaudTarnecLeo S

1 Answers

1
votes

From your comment above: "It happens but there is a delay and sometimes i have to reload page. I think i have to wait for response or something like that."

Yes, as explained in the doc, you need to wait that the Auth object has finished initializing.

This is why you should:

  • Either use the onAuthStateChanged() observer and put the desired code/ business logic in the if (user) {} block, where you are sure user is not null.
  • OR, manually check that firebase.auth().currentUser is not null before triggering the code/ business logic.

Concretely, based on what I understand from your question, you could/should call navigation.navigate("WaitingRoom") in the onAuthStateChanged() observer, as follows:

firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      user
        .sendEmailVerification()
        .then(() => {
          navigation.navigate("WaitingRoom");
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      console.log(":(");
    }
  });