firebase.functions()在React中未定义,而firebase.firestore()可以工作

时间:2020-08-05 15:37:11

标签: javascript reactjs firebase firebase-realtime-database google-cloud-functions

因此,我正在研究一个使用Firebase实现许多功能的React项目。 现在,我试图在其中使用一些HTTPS可调用函数。

但是似乎我导入“ firebase / functions”模块的方式不正确。这给了我这个错误:

TypeError: Cannot read property 'httpsCallable' of undefined

以下是我的导入和设置方法:

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';

const config = {
   // the config info here
};

  class Firebase {
    constructor() {
      app.initializeApp(config);
      this.auth = app.auth();
      this.db = app.firestore();
      this.functions = app.functions();
    }

    // trying to call the function
    doCreatePlanner = this.functions.httpsCallable('createPlanner')

应用道格的建议后:

您正在尝试在构造函数中定义this.functions之前对其进行访问。为了摆脱错误消息,您可以将对httpsCallable的调用移至构造函数中:

我这样做了

class  Firebase {
    constructor() {
        app.initializeApp(config);
        this.auth = app.auth();
        this.db = app.firestore();
        // Get the callable function reference here
        this.createPlannerCloudFunc = app.functions().httpsCallable('createPlanner')
    }
    
    doCreatePlanner = (input) =>  this.createPlannerCloudFunc(input)

它有效!

但是我还是有点困惑。

在创建/使用类时,不是总是应该首先调用构造函数吗?

因此在doCreatePlanner函数中,this.functions应该保留app.functions(),对吧?

我可以在类中做这样的功能,其中this.db持有app.firestore()

doUpdateRecord = (userRecord) =>
    // create the user in firestore
    this.db.collection(`users`).doc(userRecord.uid).set({
        // record info here
    })

1 个答案:

答案 0 :(得分:0)

引用this.functions = app.functions()指向对象的集合。指针不保存该函数,因为这些对象的类型不同。一方面,您只有一个实体,另一方面,您有一系列对象。

this.db可以容纳app.firestore(),因为这些属性的类型相同。