currentUser firebase is returning null

Asked

Viewed 30 times

-1

I’m doing a project that consists of creating two applications, I’m using firebase as a database and both are using the same database, the first application is working normally, but the second is saying that the currentUser is null and void.

First App:

async function signUpPet(
    namePetField,
    typePetField,
    agePetField,
    racesPetField,
  ) {
    let uid = await firebase.auth().currentUser.uid;
    let key = await firebase.database().ref('pets').child(uid).push().key;

    await firebase
      .database()
      .ref('pets')
      .child(uid)
      .child(key)
      .set({
        nm_pet: namePetField,
        ds_type: typePetField,
        ds_age: parseFloat(agePetField),
        ds_races: racesPetField,
        dt_createPet: format(new Date(), 'dd/MM/yyyy'),
      })
      .then(async (snapshot) => {
        let data = {
          key: key,
          namePet: namePetField,
          typePet: typePetField,
          agePet: snapshot.val().ds_age,
          racesPet: racesPetField,
          dateCreatePet: snapshot.val().dt_createPet,
        };
        setUser(data);
      });
  }

Second App:

async function signUpTimeVetSignUp(
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday,
  ) {
    let uid = await firebase.auth().currentUser.uid;
    let key = await firebase.database().ref('timeVets').child(uid).push().key;

    await firebase
      .database()
      .ref('timeVets')
      .child(uid)
      .child(key)
      .set({
        vetmonday: monday,
        vettuesday: tuesday,
        vetwednesday: wednesday,
        vetthursday: thursday,
        vetfriday: friday,
        vetsaturday: saturday,
        vetsunday: sunday,
      })
      .then(() => {
        let data = {
          mondayVet: monday,
          tuesdayVet: tuesday,
          wednesdayVet: wednesday,
          thursdayVet: thursday,
          fridayVet: friday,
          saturdayVet: saturday,
          sundayVet: sunday,
        };
        setTimeVet(data);
      });
  }

1 answer

0

hard to say only with this code. probably there is something wrong with the authentication of the second app. remembering that as soon as we reload the page firebase.auth().currentUser.uid is usually null. because it has not yet performed authentication. try to use:

let firebaseUser = null;
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    firebaseUser = user;
  } else {
    console.log('usuário não logado');
  }
});

async function signUpTimeVetSignUp(
    monday,
    tuesday,
    wednesday,
    thursday,
    friday,
    saturday,
    sunday,
  ) {
    let uid = firebaseUser.uid;
    let key = await firebase.database().ref('timeVets').child(uid).push().key;
    // ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.