简体   繁体   中英

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.

For example, I am trying to use the following code, it is a json file which is read by the system I use.

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.

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. Make sure you intialize the firebase first then use the firestore to fetch or update any kind of data.

This is firebase utils/config file where intialization of firebase is done!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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