I'm using react with firebase/firestore, I'm moving from Angular to React but I'm struggling to access the firestore database without AngularFirestore. I am able to login to firestore and obtain the user.uid, I just can't access the 'pred' collection which is nested inside each user.uid so this data is only for the user.
In Angular I access my database like this: (it works)
this.auth.user.pipe(take(1)).subscribe((user) => {
if (user) {
this.items = this.db
.collection("users")
.doc(this.user.uid)
.collection("pred")
.valueChanges();
In react I'm trying to do the same collection, doc, collection, but I can't find clear documentation how to do it.
My react attempt:
import React, { useEffect, useState } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useNavigate } from "react-router-dom";
import "./Dashboard.css";
import { auth, db, logout } from "../../services/firebase/firebase-auth";
import { query, collection, getDocs, where, doc } from "firebase/firestore";
function Dashboard() {
const [user, loading, error] = useAuthState(auth);
const [name, setName] = useState("");
const navigate = useNavigate();
const fetchData = async () => {
const userId = auth.currentUser?.uid;
const docRef = collection(db, "users");
const predictions = collection(db, "pred");
const predSnapshot = await getDocs(predictions);
const predList = predSnapshot.docs.map((doc) => doc.data());
return predList;
};
How can I return the predList which follows:
.collection("users")
.doc(this.user.uid)
.collection("pred")
path order, but using react or just plain javascript? I'm using this import { query, collection, getDocs, where, doc } from "firebase/firestore"; package but I can't see how to do it.
CodePudding user response:
To create a reference to the pred
subcollection of the current user in the new modular/v9 syntax:
collection(db, "users", userId, "pred")
CodePudding user response:
const fetchData = async () => {
const userId = auth.currentUser?.uid;
const docRef = collection(db, "users", userId as string, "pred");
const preds = await getDocs(docRef);
const predList = preds.docs.map((doc) => doc.data());
console.log(predList);
};