TypeError: Cannot read properties of undefined (reading 'indexOf') at it.fromString

Viewed 38

I am trying to order my 'orders' collection in descending order and i am getting this error and i cant seem to figure out why.

 const [orders, setOrders] = useState([]);
  useEffect(() => {
    if (user) {
      const userOrders = onSnapshot(
        doc(db, "users", user?.id, "orders").orderBy("created", "desc"));
           setOrders(
           userOrders.map((doc) => ({
           id: doc.id,
           data: doc.data(),
         }))
      );
    } else {
      setOrders([]);
    }
  }, [user]);

I am new to v9 modular firebase and if someone could help me out with this i'd appreciate it.

--UPDATE--

So i used a hardcoded value for my user?.id and also restructured my code to:

  const [orders, setOrders] = useState([]);
  useEffect(() => {
    const getData = async () => {
      if (user) {
        const collRef = doc(
          db,
          "users",
          "ZnvtmiBtrafmqHY9AegcwYU2cKV2",
          "orders"
        );
        const docSnap = await onSnapshot(collRef, orderBy("created", "desc"));
        setOrders(docSnap);
        orders.map((doc) => ({
          id: doc.id,
          data: doc.data(),
        }));
      } else {
        setOrders([]);
      }
    };
    getData();
  }, [user]);

and I am getting this error:

Orders.jsx:41 Uncaught (in promise) FirebaseError: Invalid document reference. Document references must have an even number of segments, but users/ZnvtmiBtrafmqHY9AegcwYU2cKV2/orders has 3.

I am not sure why I am getting this error.

1 Answers

There are several problems in your code:

  1. By doing doc(db, "users", user?.id, "orders").orderBy("created", "desc"); you try to call the orderBy() method on a DocumentReference, which is not possible (and actually this DocumentReference is wrongly defined). You need to call the orderBy() method on a CollectionReference.
  2. You cannot directly call map() on userOrders, since onSnapshot() attaches a listener for DocumentSnapshot events and returns a function that can be called to cancel the snapshot listener.

I would suggest you read the following documentation:


In your case, the query should be declared as follows:

const collRef = collection(db, "users", user?.id, "orders");
const q = query(collRef, orderBy("created", "desc"));

const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
 console.log(doc.id, " => ", doc.data());
});
// Or querySnapshot.docs().map(...);
Related