Firebase-在时间戳上创建了Firestore-反应 [英] Firebase - firestore createdAt timestamps - react

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

问题描述

我试图弄清楚如何在我的Firestore数据库中创建的文档中添加时间戳.

我已阅读并尝试了这篇文章中的每一项建议.

我已经阅读了该文章上的文档链接,并且无法理解为记录文档创建日期的时间戳而应该尝试执行的步骤.

在我的Firebase设置中,我有:

firebase.initializeApp(config);
const database = firebase.database();
const fsDB = firebase.firestore();
const settings = { timestampsInSnapshots: true };


export { firebase, database as default, fsDB, settings };

我真的不确定设置const是否必要,因为关于这一点的很多文章都表明它现在是firebase中的某种默认设置(在那一点上我找不到firebase文档). /p>

然后,在我的表格中,我有:

import * as firebase from '../../../firebase';
import { fsDB } from "../../../firebase";

我不确定为什么必须直接导入这些firebase文件,因为它们位于应用程序入口点,但是有几篇文章提出了建议.

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;

我也尝试过:

this.state = {createdAt: firebase.fsDB.serverTimestamp()};

this.state = {createdAt: firebase.firestore.FieldValue.serverTimestamp()};


this.state = {createdAt: firebase.FieldValue.serverTimestamp()};

这些方法都不起作用.必须有一种简单的方法可以在文档中添加时间戳,以便我可以监视它们的创建时间.为什么这么难弄清楚怎么办呢?

当我尝试时:

this.state = {createdAt: firebase.fsDB.FieldValue.serverTimestamp()};

(注意-我的Firestore保存为fsDB),

我看到一条错误消息:

TypeError: Cannot read property 'serverTimestamp' of undefined

我认为(由于我定义配置的方式)该表达式可能会读为:

this.state = {createdAt: fsDB.FieldValue.serverTimestamp()};

但是会产生相同的错误消息

firebase支持凭单建议建议:

createdAt: firebase.firestore.Timestamp.now(); 

尝试此操作时,出现错误消息:

TypeError:无法读取未定义的属性"Timestamp"

很高兴知道如何在Firestore中使用时间戳.

firebase文档说:

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

尝试此操作时,出现错误消息:

TypeError:无法读取未定义的属性'FieldValue'

我尝试了所有这些设置初始值的尝试,也尝试了对带有值的setState的单独尝试.它们都不起作用.

根据下面的Murray R的建议,我尝试了显示在{}和()中的这两个注释行.这些尝试均无效(该页面无法呈现其中包含的错误(无法编译,预期;是错误消息).我洒了;在所有可以想到的地方都可以考虑放置它们,但无法得到工作方式.

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

解决方案

要获取Firestore时间戳,firebase.firestore.FieldValue.serverTimestamp()是正确的调用.这里有个要注意的地方:此方法仅在DocumentReference .set().update()调用(或者,我相信是CollectionReference .add())中使用.例如,将新文档添加到联系人"集合时,可以将formState与新属性"createdAt"组合在一起,然后将其传递给.add()方法:

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

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

解决方案

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

这篇关于Firebase-在时间戳上创建了Firestore-反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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