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;
2
Answers
My guess it that
user
doesn’t have a value, souser?.id
becomesundefined
. You’ll want to still check whetheruser
has a value inside the second snippet too.For example: