I'm trying to connect Firestore (v 9.6.7) to my app. I'm using web 9 syntax. My code is almost directly from the guides here.
It looks like:
import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';
import { collection, getDocs } from "firebase/firestore";
// Initialize Firebase
const firebaseConfig = {
apiKey: ...
authDomain: ...,
projectId: ...,
storageBucket: ...,
messagingSenderId:...,
appId: ...,
measurementId: ...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
// Read collection from Firestore and print it
const querySnapshot = getDocs(collection(db, "Users"));
console.log(querySnapshot);
export {
db
}
The promise returned is:
Promise { "_U": 0, "_V": 0, "_W": null, "_X": null, }
What's going wrong?
Thanks.
CodePudding user response:
Friend, when I tell you I struggled with this for two straight days, I mean two 8 hour straight days.
The answer is in firebase's source.
First thing you need to do is add a metro.config.js
file to the root of your project. Inside add the following:
const { getDefaultConfig } = require("metro-config");
const { resolver: defaultResolver } = getDefaultConfig.getDefaultValues();
exports.resolver = {
...defaultResolver,
sourceExts: [
...defaultResolver.sourceExts,
"cjs",
],
};
This will allow "cjs" source extensions.
Another good way to print your collection from firestore is like so:
const db = getFirestore()
const colRef = collection(db, "collection")
getDocs(colRef)
.then((snapshot) => {
let collection = []
snapshot.docs.forEach((doc) => {
collection.push({...doc.data(), id: doc.id })
})
})
This is a nice way to print to the console in a much more friendly way.
Give this a try and see if it works. If it doesn't please comment so I can help further.
I want to tag the original stackoverflow answer for the metro.config.js file because I did not come up with this on my own but I can't find it. If I do I will edit this post with the link for credit.
Edit: found it. Credit here.