Home > other >  Firestore how to display an array of items in a collection
Firestore how to display an array of items in a collection

Time:02-06

I want to display the user's order history in user profile. Thus, I'm trying to fetch the order (which has an array of items) that matches with a userId and show it in their profile. Below is a screenshot of my firestore db.

*FB version 9, on react native

enter image description here

CodePudding user response:

You can get array of orders by calling getDoc from firebase

For example; const ordersRef = doc("configured firestore db", "name of your collection", "user id");

For more information you can read the firestore documentation https://firebase.google.com/docs/firestore/query-data/get-data

CodePudding user response:

We need to define a relationship between an order and the user who ordered it.

assume that we have orders collection with the following documents:

 {
  "R09_iuyb0gty": {
    orderId: "R09_iuyb0gty",
    createdAt: "",
    orderBy: {
      userId: "yhnbauytfredd",
      name: "Paul Allen",
    },
    items: [
      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },

      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },
    ],
  },

  "990_ggt6098765": {
    orderId: "990_ggt6098765",
    createdAt: "",
    orderBy: {
      userId: "yhnbauytfredd",
      name: "Paul Allen",
    },
    items: [
      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },

      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },
    ],
  },
}

Filters and return user specific orders


import { collection, doc, setDoc, getDocs } from "firebase/firestore";
import { getAuth } from "firebase/auth";

const getUserId = () => {
  const auth = getAuth();
  const user = auth.currentUser;

  return user.uid || null;
};

async function getOrdersByUser() {
  const userId = getUserId();

  if (!userId) return;

  const ordersRef = collection(db, "orders");
  const q = query(ordersRef, where("orderBy.userId", "==", userId));
  const querySnapshot = await getDocs(q);

  let orders = [];
  querySnapshot.forEach((doc) => {
    if (doc.data()) {
      orders.push(doc.data());
    }
  });

  return orders;
}

Fetch user's orders when component mounted


useEffect(async () => {
  const userOrders = await getOrdersByUser();

  console.log({ userOrders });
}, []);



  •  Tags:  
  • Related