Reputation: 2705
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.
I have read the documentation links on that post and I can't make sense of the steps I'm supposed to try to implement in order to record the timestamp for the document creation date.
In my firebase settings I have:
firebase.initializeApp(config);
const database = firebase.database();
const fsDB = firebase.firestore();
const settings = { timestampsInSnapshots: true };
export { firebase, database as default, fsDB, settings };
I'm really not sure if the settings const is necessary because a lot of the posts on this point suggest that it is now some kind of default in firebase (I can't find the firebase documentation on that point).
Then, in my form, I have:
import * as firebase from '../../../firebase';
import { fsDB } from "../../../firebase";
I'm not sure why it's necessary to import these firebase files directly, because they are in the app entry point, but several posts have suggested it.
class Preregistration extends React.Component {
constructor(props) {
super(props);
this.state = {selectedValue: null};
this.state = {createdAt: firebase.database.serverTimestamp()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.createdAt.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default Preregistration;
I have also tried:
this.state = {createdAt: firebase.fsDB.serverTimestamp()};
this.state = {createdAt: firebase.firestore.FieldValue.serverTimestamp()};
this.state = {createdAt: firebase.FieldValue.serverTimestamp()};
None of these approaches work. There must be a simple way to add a time stamp to a document so that I can monitor when they were created. Why is it so difficult to figure out how to do it?
When I try:
this.state = {createdAt: firebase.fsDB.FieldValue.serverTimestamp()};
(note - my firestore is saved as fsDB),
I get an error that says:
TypeError: Cannot read property 'serverTimestamp' of undefined
I thought maybe (because of the way i define my config) the expression might be meant to read:
this.state = {createdAt: fsDB.FieldValue.serverTimestamp()};
but that produces the same error message
The firebase support ticket advice suggests:
createdAt: firebase.firestore.Timestamp.now();
When I try that, I get an error that says:
TypeError: Cannot read property 'Timestamp' of undefined
It would be great to know how to use timestamps in firestore.
The firebase docs say:
var docRef = db.collection('objects').doc('some-id');
// Update the timestamp field with the value from the server
var updateTimestamp = docRef.update({
timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
When I try that, I get an error that says:
TypeError: Cannot read property 'FieldValue' of undefined
I have tried each of these things setting both the initial value as well as a separate attempt at setState with a value. None of them work.
Taking Murray R's suggestion below, I tried both of these commented lines as shown and in {} and in (). None of these attempts work (the page won't render for the errors contained within them (failed to compile, expected ; are the error messages). I have sprinkled ; at every place I can think to put them but can't get this approach to work.
handleSubmit = (formState, { resetForm }) => {
// Now, you're getting form state here!
console.log("SUCCESS!! :-)\n\n", formState);
fsDB
.collection("contact")
.add(formState)
// .set createdAt: firebase.firestore.FieldValue.serverTimestamp()
// .add 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);
});
};
Upvotes: 3
Views: 4561
Reputation: 426
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);
});
}
Upvotes: 4