skip to Main Content

I changed my code from firebase v8 to v9, I am able to write the data in db but couldn’t get and map it.

My data is stored in db like this : users >> user.uid >> orders >> paymentIntent.id,

each doc saved has amount, basket data, created

Please check mentioned screenshot.

Previous code:

useEffect(() => {
    if (user) {
      db.collection("users")
        .doc(user?.uid)
        .collection("orders")
        .orderBy("created", "desc")
        .onSnapshot((snapshot) => {
          // console.log(snapshot);
          setOrders(
            snapshot.docs.map((doc, i) => ({
              key: { i },
              id: doc.id,
              data: doc.data(),
            }))
          );
        });
    } else {
      setOrders([]);
    }
  }, [user]);

My data is stored in db like this : users >> user.uid >> orders >> paymentIntent.id,

each doc saved has amount, basket data, created

Please check mentioned screenshot.

This is firestore inserted data

firestore added data in db, screenshot

This is my new code

import { collection, doc, getDoc, getDocs, onSnapshot, orderBy, query } from 'firebase/firestore';
import React, { useEffect, useState } from 'react'
import { db } from './firebase';
import './Orders.css'
import { useStateValue } from './StateProvider';
import Order from './Order';

function Orders() {
  const [{ basket, user}, dispatch] = useStateValue();
  const [orders, setOrders] = useState([]);


useEffect(() => {
  const getDocs = async () => {
    try {
      const collRef = await getDocs(collection(db, "users", user?.id, "orders"));
      // const collRef = doc(db, "users", user?.id, "orders"));
      // const collRef = collection(db, "users", user?.id, "orders"));

      const orderedRef = query(collRef, orderBy("created", "desc"));
      const docSnap = onSnapshot(orderedRef, (snapshot) => {
        snapshot.map((doc) => ({
          id: doc.id,
          data: doc.data(),
        }));
        setOrders(docSnap);
      });
    } catch (err) {
      console.log(err.message);
    }
  };
  getDocs();
}, [user]);

  return (
    <div className="orders">
      <h3>Your Orders</h3>
      <div className="orders__order">
        {orders?.map((order, i) => (
          <Order key={i} order={order} />
        ))}
      </div>
    </div>
  );
}

export default Orders;

Console, screenshot

2

Answers


  1. Chosen as BEST ANSWER
    useEffect(() => {
      if (user) {
        try {
                const collRef = collection(db, "users", user?.uid, "orders");
                const orderedRef = query(collRef, orderBy("created", "desc"));
                const docSnap = onSnapshot(orderedRef, (querySnapshot) => {
                  const orderArray = [];
                  querySnapshot.forEach((doc) => {
                    orderArray.push({
                      id: doc.id,
                      data: doc.data()
                    })
                  })
                  setOrders(orderArray);
                 });
              } catch (err) {
                console.log(err.message);
              } 
      } else {
        console.log("not found");
        setOrders([]);
      }
    }, [user]);
    
    

  2. My guess it that user doesn’t have a value, so user?.id becomes undefined. You’ll want to still check whether user has a value inside the second snippet too.

    For example:

    useEffect(() => {
      const getDocs = async (user: User) => {
        try {
          const collRef = await getDocs(collection(db, "users", user.id, "orders"));
    
          ...
        } catch (err) {
          console.log(err.message);
        }
      };
      if (user) {
        getDocs(user!);
      }
    }, [user]);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search