firebase Display Name is null - javascript

I'm trying to print firebase display name.
its showing after login. but after registrtion its showing null value. I'm using react-firebase-hook
const [userAuthenticate,loadingAuthenticate] = useAuthState(auth)
const [update,setUpdate] = useState(auth)
useEffect(()=>{
const tokenUpdate = async()=>{
if(userAuthenticate && update){
console.log(userAuthenticate.displayName); // Showing Null
navigate('/');
}
}
tokenUpdate();
},[userAuthenticate,update]);
const onSubmit = async(data) => {
const name = data.name;
const email = data.email;
const password = data.password;
await createUserWithEmailAndPassword(email, password);
await updateProfile({ displayName: name });
await sendEmailVerification(email)
setUpdate(true);
};

Updating the profile does not automatically refresh the profile in the current application. You'll need to reload the user's profile after the call to updateProfile completes.

Related

Error : Function CollectionReference.doc() cannot be called with an empty path

This is the javascript code I was running and ended up in getting this error in the javascript console:
Error : Function CollectionReference.doc() cannot be called with an empty path
Other people did answer the same question, but it didn't work in my case.
const firebaseApp = firebase.initializeApp({
// my configuration here
});
const db = firebaseApp.firestore();
const auth = firebaseApp.auth();
const user = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
// User is signed in, see docs for a list of available properties
// https://firebase.google.com/docs/reference/js/firebase.User
var uid = user.uid;
console.log("Logged in");
// ...
} else {
// User is signed out
// ...
alert("you are not logged in");
window.location.href = "Auth.html";
}
});
const Publish = () => {
const user = firebase.auth().currentUser;
// const displayName = user.displayName;
const email_value = user.email;
// const photoURL = user.photoURL;
// const emailVerified = user.emailVerified;
// const uid = user.uid;
let blogTitle = document.getElementById("exampleFormControlInput1").value;
let articleField = document.getElementById("exampleFormControlTextarea1").value;
var docName = blogTitle.toString()
db.collection(email_value).doc(docName).set({
title: docName,
article: articleField,
})
}
I tried the solutions given by other people like -- ${docName} but that didn't work. I am really confused at this point and don't know what I did wrong with the javascript.

Is there a library for promptForCredentials with firebase?

I am trying to learn how to delete users from the Firebase Auth provided, but when I click on the delete button on my html it gives me Uncaught ReferenceError: promptForCredentials is not defined
I can't find any information on if I am suppose to import it anywhere. I'm using plain vanilla javascript.
Here is my code:
my html includes for scripts:
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.2.7/firebase-database.js"></script>
javascript:
const firebaseConfig = {//my app information}
firebase.initializeApp(firebaseConfig);
const auth = firebase.auth();
const database = firebase.database();
const fname = document.querySelector('#fname');
const lname = document.querySelector('#lname');
const email = document.querySelector('#email');
const password = document.querySelector('#password');
const confirm_password = document.querySelector('#confirmpassword');
const deleteConfirmed = document.querySelector('.deleteConfirmed');
const passConfirmed = document.querySelector('#deletePass');
auth.onAuthStateChanged(user => {
if(user) {
const user = auth.currentUser
const database_ref = database.ref('users/' + user.uid).on('value', (snapshot) => {
fname.value = snapshot.val().first_name;
lname.value = snapshot.val().last_name;
email.value = snapshot.val().email;
});
deleteConfirmed.addEventListener('click', () => {
const credential = promptForCredentials();
user.reauthenticateWithCredential(credential).then(() => {
// User re-authenticated.
}).catch((error) => {
// An error ocurred
// ...
});
})
} else {
location.href = "/login";
}
});
It looks like you copied code from the Firebase documentation on re-authenticating a user, which shows:
const user = firebase.auth().currentUser;
// TODO(you): prompt the user to re-provide their sign-in credentials
const credential = promptForCredentials();
user.reauthenticateWithCredential(credential).then(() => {
// User re-authenticated.
}).catch((error) => {
// An error occurred
// ...
});
That TODO there means that you have to implement the prompt for the credentials of the user in whatever way works for your app, and then pass them to the reauthenticateWithCredential API.

Firestore database won't appear

I'm new with Firebase and I'm still learning how it works. I've created a login, signup and logout sections. The users appear registrated and are saved in the authentication section, but I also want to have their data in database when they register for the first time. I thought of using Firestore Database. The problem is that everything seems to work, but nothing appears in my database section. At first I thought that I was not passing any user auth to the function, so i created a condition to test if there's no user auth, then show a warning. However, there's no warning so it means that I passed it properly.
This is how the sign up function works:
export const SignUp = () => {
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const displayName = useRef();
const email = useRef();
const password = useRef();
const passwordConfirmRef = useRef();
const handleSubmit = async e => {
e.preventDefault();
if (password.current.value !== passwordConfirmRef.current.value) {
return setError("Passwords do not match");
}
try {
setError("")
setLoading(true)
const { user } = await auth.createUserWithEmailAndPassword(email.current.value, password.current.value)
const userRef = await handleUserProfile(user, displayName.current.value)
console.log(userRef)
} catch {
setError("Failed to create an account")
}
setLoading(false)
}
I create the user with auth.createUserWithEmailAndPassword and then I pass the user to handleUserProfile
Here's handleUserProfile function:
export const handleUserProfile = async (userAuth, additionalData) => {
if (!userAuth) {
console.warn("No userAuth")
return
}
const { displayName, email } = userAuth;
const timestamp = new Date()
try {
return await firestore.collection("users").add({
displayName,
email,
timestamp,
...additionalData
})
} catch (err) {
console.log(err)
}
return null;
};
Then, nothing appears in my database and nothing gets added. I'm not sure what I'm doing wrong.
The firestore.collections().add function is adding objects (key: value pairs).
It looks like you're not passing an object into handleUserProfile:
const userRef = await handleUserProfile(user, displayName.current.value)
Passing an object into additionalData should solve your issue.

Correct way to pass async eerror

I have a function which uses Firebase auth to update a user's email:
export const updateEmail = async (email) => {
const user = auth.currentUser;
return user.updateEmail(email);
};
It is used in a function which gets an email from a form (in React) and tries to update the email. If there is an error, we change the state to reflect that.
handleSave = (e) => {
const email = e.target.email.value;
updateEmail(email).catch((err) => {
this.setState({ didError: true, emailError: err.message });
});
};
However, when an error occurs, in the console I get:
My question is: why does this still say 'Uncaught'? Does the .catch() in handleSave not take care of that?
update
Link to relevant Firebase docs
Assuming updateEmail returns a prmise, I guess you can try:
export const updateEmail = (email) => { // no need for async here
const user = auth.currentUser;
return user.updateEmail(email);
};
handleSave = async (e) => {
const email = e.target.email.value;
try{
await updateEmail(email);
}catch(err){
this.setState({ didError: true, emailError: err.message });
}
};
I'm not quite sure since I don't know so much about Firebase, let me suggest something.
export const updateEmail = async (email) => {
const user = auth.currentUser;
const response = await user.updateEmail(email);
if ( response.error ) {
throw new Error( response.error );
}
return "something else";
};

How do I add a user to my Firebase DB with it's unique id when I first create a user for authentication

This may seem like an obvious question, but i'm having trouble creating a user inside of my Firebase db. I'm very new to firebase and coding for that matter.
How I understand it to be is when a user clicks the sign up button, a user with the newly authenticated uid will be created under 'object/users". However the user is always null. In the google documentation it says that sometimes the user is null because it hasn't finished initializing the user. And to put it inside of onAuthStateChanged. This works, however, if I did this a user would be created/overwritten every time they log in or log out.
I suppose what I'm looking for is some solution to create a user inside of my firebase db when a user first signs up with valid information.
Here is my code:
function LoginCtrl($scope) {
$scope.txtEmail = document.getElementById('txtEmail');
$scope.txtPassword = document.getElementById('txtPassword');
$scope.btnLogin = document.getElementById('btnLogin');
$scope.btnSignUp = document.getElementById('btnSignUp');
$scope.btnLogout = document.getElementById('btnLogout');
btnLogin.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
});
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
createUser();
});
function createUser() {
var user = firebase.auth().currentUser;
if (user != null) {
const dbRefObject = firebase.database().ref().child('object');
const dbRefList = dbRefObject.child("users/" + user.uid);
dbRefList.set({
name: "jim",
});
}
}
btnLogout.addEventListener('click', e => {
firebase.auth().signOut();
});
firebase.auth().onAuthStateChanged(firebaseUser => {
if (firebaseUser) {
console.log(firebaseUser);
btnLogout.classList.remove('hide');
btnLogin.classList.add('hide');
} else {
console.log('not logged in');
btnLogout.classList.add('hide');
btnLogin.classList.remove('hide');
}
})
}
The culprit is in these three lines:
const promise = auth.createUserWithEmailAndPassword(email, pass);
promise.catch(e => console.log(e.message));
createUser();
You are firing off createUser() too soon. In the above code fragment, this happens right after starting the (asynchronous) registration process – the SDK never had a chance to actually create the user in the auth database!
The createUserWithEmailAndPassword returns a promise, as reflected in your local variable. What you need to do here is chaining the two calls, i.e. start the database manipulation after the promise is fulfilled.
Try this:
// inside the click handler
btnSignUp.addEventListener('click', e => {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
auth.createUserWithEmailAndPassword(email, pass)
.then(user => createUser(user)) // <-- important!
.catch(e => console.log(e.message));
});
function createUser(user) {
// no need for currentUser if you pass it in as an argument
if (user) {
...
}
}

Categories