I am setting up a simple webpage with Firebase Authentication and a Firestore database which takes user inputs from a form, adds the inputs as a collection document in Firestore, and then also outputs the whole collection. Each document in the collection has two fields, the Name and the Body of the document. The goal is to allow users to make posts on the website using the input form. Everything I described is working, but now I would like to display the user.displayName with the post, to show who exactly created the user input, and that's what I can't figure out how to do. Here's the relevant code, from the script.js of the website:
const createForm = document.querySelector('#create-form');
createForm.addEventListener('submit', (e) => {
e.preventDefault();
db.collection('forumposts').add({
Body: createForm['body'].value,
//the line below is what I cannot figure out how to set up
Name: string(user.displayName)
}).then(() => {
//reset the form
createForm.reset();
}).catch(err => {
console.log(err.message)
})
});
I'm still learning about JavaScript, so I apologize if I am missing something obvious. I know the user's displayName (which is collected upon sign up) is being collected properly, as I can log it to the console and it shows up correctly. I just cannot figure out how to then add it as a field in this database collection input. I have tried searching here on SO for related questions, but am only getting questions related to how the user can add a display name on sign-up. I already have the display name, I just need to input it into the database. Any help would be greatly appreciated!
Where is the "user" defined? That could be null if no user is logged in so it's better to check for the user.
const createForm = document.querySelector('#create-form');
createForm.addEventListener('submit', (e) => {
e.preventDefault();
const user = firebase.auth().currentUser
if (user) {
db.collection('forumposts').add({
Body: createForm['body'].value,
Name: user.displayName || "No username"
}).then(() => {
//reset the form
createForm.reset();
}).catch(err => {
console.log(err.message)
})
} else {
console.log("NO user logged in")
}
});
You don't need the String() constructor. If displayName is defined it'll be a string. You can use if (user.displayName) before adding the post to check if user has a display name.
It's String(), not string(). As long as displayName is a property of user, it will be added to the database.