Setting a created timestamp in Firestore with React

点点圈 提交于 2020-07-10 08:15:18

问题


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.


回答1:


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.




回答2:


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,
})


来源:https://stackoverflow.com/questions/55753570/setting-a-created-timestamp-in-firestore-with-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!