Home > Blockchain >  Firebase web realtime database stiring user id as undefined
Firebase web realtime database stiring user id as undefined

Time:12-08

I have a create user and login authentication setup with firebase realtime database. I have a user field in my database where I will store user data. However, I would like to create a child element under the user field that is the user id then the user information can be displayed under that child. So far I have tried to create such a field with this:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-app.js";
import { getDatabase, set, ref, update } from "https://www.gstatic.com/firebasejs/9.13.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut} from "https://www.gstatic.com/firebasejs/9.13.0/firebase-auth.js";

//Signup section
signup.addEventListener('click',(e) => {
    var username = document.getElementById('signup-user').value;
    var email = document.getElementById('signup-email').value;
    var schoolID = document.getElementById('signup-id').value;
    var password = document.getElementById('signup-pwd').value;
    
        createUserWithEmailAndPassword(auth, email, password, schoolID)
            .then((userCredential) => {
                // Signed in 
                const user = userCredential.user;

                update(ref(database, "user/"  user.id),{
                    username: username,
                    schoolID: schoolID,
                    email: email
                })
                alert('User Created!');
                // ...
            })
            .catch((error) => {
                const errorCode = error.code;
                const errorMessage = error.message;
                
                alert('Error please try again');
                // ..
            });
    });

But it only gives me an undefined field in my realtime database:

firebase error

Not only that but it overwrites the previous entry every time a make an new user.

CodePudding user response:

userCredential.user is a User type object, which is a subclass of UserInfo. As you can see from the linked API documentation, User doesn't have an property called id. It will always be undefined.

What you want instead is uid.

update(ref(database, "user/"   user.uid), {...})
  • Related