I am trying to figure out how to add timestamps to documents created in my firestore database.
I have read and tried each and every one of the suggestions in this post.<
To get the Firestore timestamp, firebase.firestore.FieldValue.serverTimestamp()
is the correct call. Here's the catch: this method is only used within a DocumentReference .set()
or .update()
call (or, I believe, a CollectionReference .add()
). For example, when adding a new document to your "contact" collection, you might combine formState with the new property 'createdAt' as you pass it to the .add()
method:
handleFormSubmit(event) {
// Now, you're getting form state here!
console.log("SUCCESS!! :-)\n\n", formState);
fsDB
.collection("contact")
.add({
...formState,
createdAt: firebase.firestore.FieldValue.serverTimestamp()
})
.then(docRef => {
console.log("docRef>>>", docRef);
this.setState({ selectedValue: null });
resetForm(initialValues);
})
.catch(error => {
console.error("Error adding document: ", error);
});
}