I'm working on connecting a Firestore database collection to a Next.js app. The app is very simple, as I am just fetching data and displaying it on the screen. I have a collection with two items in Firestore right now, and I'm trying to get it to console.log()
to verify that it is connecting. However, when I do, the console shows me two Arrays, but they don't seem to hold any of the data from my database.
I am currently using this code to log the data to the console:
import React, { useEffect, useState } from 'react'
import {collection, getDocs} from 'firebase/firestore';
import db from '../firebase/config'
import { Box } from '@chakra-ui/react'
import ProductCard from './ProductCard'
const Products = () => {
const [products, setProducts] = useState([])
useEffect(() => {
;(async () => {
const colRef = collection(db, 'products')
const snapshots = await getDocs(colRef)
const docs = snapshots.docs.map((doc) => {
const data = doc.data()
data.id = doc.id
return data
})
setProducts(docs)
console.log(docs)
})()
}, [])
I can provide the rest of the code, if necessary.
My firebase config file looks like this:
import { initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore';
const firebaseConfig = {
apiKey: "---",
authDomain: "---",
projectId: "---",
storageBucket: "---",
messagingSenderId: "---",
appId: "---",
measurementId: "---",
};
const app = initializeApp(firebaseConfig);
const db = getFirestore(app)
export default db
The Arrays I get look like this:
The database currently looks like this:
Does anybody have an idea, or can point me in the right direction? Thanks in advance!
CodePudding user response:
From your database screenshot we can deduce that products
is not a root collection but a subcollection of a document (which actually does not exist). (See last note at the bottom)
So you need to declare the CollectionReference
with the entire path of the (sub)collection. We don't know the name of the root collection and we just see a part of the ID of the parent document (cocoworksco...
) but you should declare the subcollection CollectionReference
as follows:
let colRef = collection(db, 'rootCollection/cocoworksco.../products');
let querySnapshot = await getDocs(colRef);
// ...
Note that they are many different possibilities to declare the subcollection: For example, collection(db, 'rootCollection', 'cocoworksco...', 'products')
or collection(db, 'rootCollection', 'cocoworksco.../products');
are also valid.
Note also that we are actually not sure that the path of the subcollection is composed of three parts since we don't see the full path on the screenshot. It is possible that it is deeper, e.g. rootCollection/doc1/subCol1/cocoworksco.../products
.