jeudi 28 mai 2020

Add users` extra data to firestore when they sign in first time with web Firebase firestore

unsubscribeFromAuth = null; //memory leak

  componentDidMount() {
    this.unsubscribeFromAuth = auth.onAuthStateChanged(user => {
      this.setState({ currentUser: user });
      if (user === null)
        return;

      // user data
      const uid = user.uid;
      const photoURL = user.photoURL;
      const name = user.displayName;      

      const userRef = firestore.collection('Users');
      userRef.where('uid','==',uid).get().then((querySnapshot) => {
        console.log("uid size : ",querySnapshot.size);
        // add user extra data when first sign in.
        if (querySnapshot.size === 0) {
          firestore.collection('Users').add({
            uid: uid,
            photoURL: photoURL,
            name: name,
          })
          .then((docRef) => {
            console.log("Document written with ID: ", docRef.id);
          })
          .catch((error) => {
            console.error("Error adding document: ", error);
          });
        }
      });
    });
  }

My code is like this. But when I sign in, querySnapshot.size is 0 and it add user`s data again and again even though there are already user data.

enter image description here enter image description here

Like these, they have same uids but signing in made again and again. Is there any problem when I program like this?




Aucun commentaire:

Enregistrer un commentaire