使用React在Firestore中设置创建的时间戳 [英] Setting a created timestamp in Firestore with React

查看:69
本文介绍了使用React在Firestore中设置创建的时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将文档添加到表单的Firestore集合( inboxItems ) onSubmit 中.

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();
}

如何将 created 字段作为时间戳字段,并以当前时间戳作为值?跨用户和时区必须保持一致.

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.

我看到了firebase.firestore.FieldValue.serverTimestamp()"rel =" nofollow noreferrer> firebase文档,但目前尚未设置字段值.我想避免执行额外的操作来更新字段.

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.

推荐答案

由于我使用Firebase身份验证,因此我会通过上下文API使用根App组件初始化firebase.我设法通过在Firebase设置文件中添加帮助程序来解决此问题:

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();
  }
}

然后:

this.props.firebase.inboxItems().add({
  created: this.props.firebase.fieldValue.serverTimestamp(),
  name: this.state.newInboxItemName,
})

这篇关于使用React在Firestore中设置创建的时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆