I am currently developing an application using React and Node.js for the server, with Firebase Auth and Firestore integration.
However, I have encountered a problem. When I create a user, everything seems to work fine. The user is created successfully, their UID and data are stored in the database. But when I try to retrieve the user data, it returns as undefined:
async function getUserData(uid) {
const docRef = doc(db, `users/${uid}`);
const docSnapshot = await getDoc(docRef);
console.log(docSnapshot);
const data = docSnapshot.data();
console.log(` data: ${data}`);
return data;
}
The console output shows that the docSnapshot is correct, but the .data() call afterwards results in undefined:
User data is not being displayed.
Here is how I create users using the Firebase-admin SDK to ensure only admins can create new users:
async function createUser(email, password, name, role) {
axios
.post('http://localhost:5000/api/user', {
email: email,
password: password,
name: name,
role: role,
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
axios.get('http://localhost:5000/api/user/info').then((info) => {
const docRef = doc(db, `users/${info.data.uid}`);
setDoc(docRef, { email: email, name: name, role: role });
});
}
Server-side code:
app.post('/api/user', jsonParser, (req, res) => {
const user = req.body;
getAuth()
.createUser({
email: user.email,
password: user.password,
displayName: user.name,
})
.then((userRecord) => {
console.log(userRecord);
app.get('/api/user/info', (req, res) => {
res.send(userRecord);
});
})
.catch((err) => {
console.log(err);
});
});