Home > Software design >  Firebase get data from Firestore v9 react
Firebase get data from Firestore v9 react

Time:02-24

I am trying to get order details from firestore using following function. But here it does not send any response back and shows that docSnap.data() is not a function

My data base structure is - User/userid/orders/data

How can i get data as response without any error?

Here is my code below -

import React, { useState, useEffect } from "react";
import { db } from "./firebase";
import { collection, doc, getDoc, orderBy } from "firebase/firestore";
import "./Orders.css";
import { useStateValue } from "./StateProvider";

const Orders = () => {
  const [{ basket, user }, dispatch] = useStateValue();
  const [orders, setOrders] = useState([]);
  useEffect(async () => {
    console.log(user?.uid);
    try {
      const docRef = doc(db, `${user?.uid}/orders/`);
      const docSnap = await getDoc(docRef);
      console.log(docSnap);
    } catch (e) {
      console.log(e);
    }
  }, []);
  return (
    <div className="orders">
      <h1>orders here</h1>
    </div>
  );
};

export default Orders;

Here is the entire path to the document which i expect funtion to read.

enter image description here

CodePudding user response:

If db is a FirebaseFirestore object, this makes no sense:

const docRef = doc(db, `${user?.uid}/orders/`);
const docSnap = await getDoc(docRef);

You're creating a reference to a document named orders in a collection user?.uid. This does not match your data structure, which would be:

const ordersRef = collection(db, `users/${user?.uid}/orders`);

So now ordersRef is a collection to the orders subcollection for the specific user. You can then read if by calling getDocs:

const ordersQuerySnapshot = await getDocs(ordersRef);

And loop through them with:

ordersQuerySnapshot.docs.forEach((doc) => {
  console.log(doc.id, doc.data());
})
  • Related