I have a firestore database with 2 collections: users and products. Users has a ‘cart’ field (type: array) which stores the uniqueName (field in products) of the products added to cart by a user. I fetched the ‘cart’ array and now, for each item, I want to fetch the product doc so I can access each product’s individual fields.
*currentUserCart stores the elements from the cart array: strings with the unique product name based on which I do the query in fetchProducts().
I tried this, but I get the correct products only if I click again wherever on the modal screen
export const Navbarr = ({items}) => {
const [user, error] = useAuthState(auth);
const [cartItems, setCartItems]=React.useState(0);
const [open, setOpen] = React.useState(false);
const [currentUserCart, setCurrentUserCart]=React.useState([]);
const [currentProducts, setCurrentProducts]=React.useState([]);
const handleOpen = () => {
fetchUserCart();
setOpen(true);
fetchProducts();
};
const fetchProducts=async()=>{
const products=[];
currentUserCart.forEach(async(item)=>{
const q = query(collection(db, "products"), where("uniqueName", "==", item));
const doc = await getDocs(q);
const data = doc.docs[0].data();
setCurrentProducts(currentProducts=>[...currentProducts, data]);
})
console.log(currentProducts);
}
const fetchUserCart = async() =>{
const q = query(collection(db, "users"), where("uid", "==", user?.uid));
const doc = await getDocs(q);
const data = doc.docs[0].data();
setCurrentUserCart(data.cart);
console.log('cart '+currentUserCart);
}
const handleClose = () => setOpen(false);
const fetchUserCartItems=async()=>{
const q = query(collection(db, "users"), where("uid", "==", user?.uid));
const doc = await getDocs(q);
const data = doc.docs[0].data();
let cartItemsClone=data.cartItems;
setCartItems(cartItemsClone);
}
React.useEffect(() => {
fetchUserCartItems();
fetchUserCart();
fetchProducts();
}, [user], [currentUserCart], [currentProducts]);