简体   繁体   English

reactjs中firestore的新文档参考

[英]new document reference of firestore in reactjs

I am using reactjs and are trying to set the "value" of a field in a document of a collection in firestore as a documentreference of another document.我正在使用 reactjs 并试图将 firestore 中集合文档中字段的“值”设置为另一个文档的文档引用。

For example, I am trying to use the following code, it is a json file which is read by the system I use.例如,我正在尝试使用以下代码,它是一个由我使用的系统读取的 json 文件。

import * as firebase from 'firebase';
require("firebase/firestore");

var collectionMeta={
    "users":{
        "fields":{
            "firstname":"",
            "lastname":"",
            "email": "",
            "gender":"",
            "birthday":"",
            "group":"",
            "subGroups":"",
            "roles":"-",
            "code":""
        },
        "collections":[],
    },
    "announcements":{
        "fields":{
            "title":"",
            "content":"",
            "active":false,
            "start":"",
            "end":"",
            "group": new firebase.firestore.DocumentReference("/groups/docID")
        },
        "collections":[],
    },
    "groups":{ 
        "fields":{
            "name":"",
            "registerCode":""
        },
        "collections":[]
    },
}
module.exports = collectionMeta;

At the moment, I am getting an error on the "new firebase.firestore.DocumentReference("/groups/docID")" part.目前,我在“new firebase.firestore.DocumentReference("/groups/docID")”部分遇到错误。

The error I get:我得到的错误:

Uncaught Error: This constructor is private. Use firebase.firestore().doc() instead.

But when I try that, I get the following error:但是当我尝试这样做时,我收到以下错误:

Firebase: No Firebase App '[DEFAULT]' has been cre…- call Firebase App.initializeApp()

It is already Initialized, because if I remove that whole line, all is fine.它已经初始化,因为如果我删除整行,一切都很好。

What to do?该怎么办?

The issue could be of the order, where you are using firebase.问题可能与您使用 firebase 的顺序有关。 Make sure you intialize the firebase first then use the firestore to fetch or update any kind of data.确保首先初始化 firebase,然后使用 firestore 获取或更新任何类型的数据。

This is firebase utils/config file where intialization of firebase is done!这是 firebase utils/config 文件,其中完成了 firebase 的初始化!

import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";

const firebaseConfig = {
  apiKey: process.env.NEXT_PUBLIC_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
  storageBucket: "mygiene-f2d83.appspot.com",
  messagingSenderId: "sender_id",
  appId: "app_id",
  measurementId: "measurement-id",
};

// Initialize Firebase

// this if condition checks if your firebase app is already intialized then it // stops it from re-initializing again
if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
} 

// only exporting firebase auth and firestore. 
export const auth = firebase.auth();
export const firestore = firebase.firestore();

Then simply use it by importing it in other file as follows然后只需通过将其导入其他文件来使用它,如下所示

import { firestore } from "../../firebase/utils";
import { useContext, useEffect, useState } from "react";

export const Component = () => {
  const [product, setproduct] = useState();

useEffect(async () => {
    const productRef = await firestore.doc("products/grooming_kit").get();
    const { id } = productRef;
    setproduct({ ...productRef.data(), pId: id });
  }, []);


return(<>
//Simply use the value stored over state however you linke
</>)
}

Voila!瞧! :) Hope this helps. :) 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM