Reputation: 443
I'm adding a document to a firestore collection (inboxItems
) onSubmit
of a form.
onCreateInboxItem = event => {
this.props.firebase.inboxItems().add({
name: this.state.newInboxItemName,
created: '', // I need a timestamp field here
})
this.setState({ name: '' });
event.preventDefault();
}
How do I get the created
field to be a timestamp field, with current timestamp as a value? It would need to be consistent across users and timezones.
I see firebase.firestore.FieldValue.serverTimestamp()
mentioned in the firebase docs, but at this point the field value isn't set yet. I would like to avoid an extra operation to update the field.
Upvotes: 0
Views: 2887
Reputation: 443
Since I use firebase authentication, I initialize firebase with the root App component via the context API. I managed to solve it by adding a helper in my Firebase settings file:
class Firebase {
constructor() {
app.initializeApp(config);
/* Helper */
this.fieldValue = app.firestore.FieldValue;
/* Firebase API's */
this.db = app.firestore();
}
}
And then:
this.props.firebase.inboxItems().add({
created: this.props.firebase.fieldValue.serverTimestamp(),
name: this.state.newInboxItemName,
})
Upvotes: 0
Reputation: 17269
You can do:
created: new Date(),
or:
created: firebase.firestore.Timestamp.fromDate(new Date()),
Alternatively you could use a cloud function, as described here, though that might be overkill.
Upvotes: 1