I'm using Google Firebase for my backend. I have a register form that the user fills out.
Once the process is successful, user is directed to the home page where it should say:
"Welcome, {user's firstName}"
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const [phoneNum, setPhoneNum] = useState('');
const onSignUp = () => {
auth
.createUserWithEmailAndPassword(email, password)
.then(userCredentials => {
firebase
.firestore()
.collection('users')
.doc(firebase.auth().currentUser.uid)
.set({
firstName,
lastName,
email,
phoneNum
});
const user = userCredentials.user;
console.log('Registered with:', user.email);
console.log(user.firstName);
})
.catch(error => console.log(error.message));
};
When I console log user.email it works, however when I console log firstName, it logs as undefined. When I check firebase, it has registered user with all the fields populated (firstName, lastName, phoneNum).
How can I retrieve the firstName of the user?
You're trying to access information from Firebase authentication user data which is not defined there.
Refactor code as below:
const onSignUp = () => {
auth
.createUserWithEmailAndPassword(email, password)
.then(async (userCredentials) => {
const usersRef = firebase.firestore().collection("users");
const user = userCredentials.user;
const userId = user.uid;
// Add new user to USERS' collection
await usersRef.doc(userId).set({
userId,
firstName,
lastName,
email,
phoneNum,
});
// Fetch registered user information
const userDoc = await usersRef.doc(userId).get();
const regiteredUser = userDoc.data();
console.log(
"Registered with:",
regiteredUser.email,
regiteredUser.firstName,
firstName.lastName
);
})
.catch((error) => console.log(error.message));
};