From b45f6c6c703e9f85967d09cc457f4af693d36893 Mon Sep 17 00:00:00 2001 From: Hemanth kumar Date: Sun, 12 May 2024 17:56:24 +0530 Subject: [PATCH] retrive fixed (#73) --- src/App.js | 6 +- src/components/product/index.js | 4 +- src/components/quantityBox/index.js | 31 +++++---- src/pages/Details/index.js | 36 ++++------- src/pages/Home/index.js | 2 - src/pages/cart/index.js | 99 ++++++++--------------------- 6 files changed, 67 insertions(+), 111 deletions(-) diff --git a/src/App.js b/src/App.js index bbdc9a3..fb2b2a0 100644 --- a/src/App.js +++ b/src/App.js @@ -55,7 +55,7 @@ function App() { useEffect(()=>{ fetchCartProducts() - },[]) + },[isLogin]) const fetchCartProducts = async () => { try { @@ -96,7 +96,6 @@ function App() { useEffect(() => { getData(); - getCartData(); const is_Login = localStorage.getItem("isLogin"); setIsLogin(is_Login); @@ -210,7 +209,8 @@ function App() { isopenNavigation, setIsopenNavigation, cartCount, - setCartCount + setCartCount, + fetchCartProducts }; return data && data.productData ? ( diff --git a/src/components/product/index.js b/src/components/product/index.js index fe8a0c1..672866b 100644 --- a/src/components/product/index.js +++ b/src/components/product/index.js @@ -98,9 +98,9 @@ const Product = (props) => { const user=localStorage.getItem('uid') const cartRef = doc(db, 'carts', user); const productRef = doc(cartRef, 'products', `${item.id}`); - await setDoc(productRef, {...item, quantity: 1}); + await setDoc(productRef, {...item, quantity: 1}) setIsadded(true) - context.setCartCount(context.cartCount+1); + context.fetchCartProducts(); } catch (error) { console.error('Error adding item to cart:', error); } diff --git a/src/components/quantityBox/index.js b/src/components/quantityBox/index.js index aea4950..17beede 100644 --- a/src/components/quantityBox/index.js +++ b/src/components/quantityBox/index.js @@ -3,24 +3,36 @@ import React, { useState, useEffect } from 'react'; import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp'; import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'; +import { db } from '../../firebase'; +import { doc, updateDoc } from 'firebase/firestore'; const QuantityBox = (props) => { - const [inputValue, setinputValue] = useState(1); + const [inputValue, setinputValue] = useState(props.quantity); const [cartItems, setcartItems] = useState([]); - + const uid = localStorage.getItem("uid"); useEffect(() => { setcartItems(props.cartItems); //setinputValue(props.item.quantity) }, [props.cartItems]) + const updateCart=(items)=>{ props.updateCart(items) } - - + const updateDb = async (uid, cartItemId, newData) => { + const cartItemRef = doc(db, 'carts', uid, 'products', cartItemId); + + try { + await updateDoc(cartItemRef, newData); + console.log('Cart item updated successfully.'); + } catch (error) { + console.error('Error updating cart item:', error); + } + }; + // const plus = () => { // setinputValue(inputValue + 1) @@ -41,13 +53,12 @@ const QuantityBox = (props) => { { + async () => { setinputValue(inputValue + 1); const _cart = props.cartItems?.map((cartItem, key) => { return key === parseInt(props.index) ? { ...cartItem, quantity: inputValue+1 } : {...cartItem} - }); - + await updateDb(uid,`${props?.item?.id}`,_cart[props?.index]) updateCart(_cart); setcartItems(_cart); @@ -59,7 +70,7 @@ const QuantityBox = (props) => { { + async () => { if (inputValue !== 1) { setinputValue(inputValue - 1) } @@ -67,9 +78,7 @@ const QuantityBox = (props) => { const _cart = props.cartItems?.map((cartItem, key) => { return key === parseInt(props.index) ? { ...cartItem, quantity: cartItem.quantity !== 1 ? inputValue-1 : cartItem.quantity } : {...cartItem} }); - - - + await updateDb(uid,`${props?.item?.id}`,_cart[props?.index]) updateCart(_cart); setcartItems(_cart); diff --git a/src/pages/Details/index.js b/src/pages/Details/index.js index 0e0f159..3e7525e 100644 --- a/src/pages/Details/index.js +++ b/src/pages/Details/index.js @@ -21,7 +21,7 @@ import MapComponent from '../../components/map/ITEMmap'; import { Email } from '@mui/icons-material'; import useLoggedInUserEmail from '../../Hooks/useLoggedInUserEmail'; import { db } from '../../firebase'; -import { doc, setDoc } from 'firebase/firestore'; +import { collection, doc, getDocs, setDoc } from 'firebase/firestore'; @@ -117,7 +117,6 @@ const DetailsPage = (props) => { setActiveSize(index); } - const plus = () => { setinputValue(inputValue + 1) } @@ -129,8 +128,6 @@ const DetailsPage = (props) => { } - - useEffect(() => { window.scrollTo(0, 0) setIsLoading(true); @@ -181,7 +178,7 @@ const DetailsPage = (props) => { showReviews(); - getCartData("https://mavrick-1.github.io/DataApi/data.json"); + fetchCartProducts() setIsLoading(false); @@ -259,8 +256,6 @@ const DetailsPage = (props) => { const addToCart = async (item) => { try { - console.log("not global in comp prod index",item) - console.log(item.id) const user=localStorage.getItem('uid') const cartRef = doc(db, 'carts', user); const productRef = doc(cartRef, 'products', `${item.id}`); @@ -272,24 +267,21 @@ const DetailsPage = (props) => { } }; - const getCartData = async (url) => { + const fetchCartProducts = async () => { try { - await axios.get(url).then((response) => { - - - response.data.cartItems.length!==0 && response.data.cartItems.map((item)=>{ - - if(parseInt(item.id)===parseInt(id)){ - setisAlreadyAddedInCart(true); - } - }) - }) - + const cartRef = doc(db, 'carts', localStorage.getItem("uid")); + const productsCollectionRef = collection(cartRef, 'products'); + const querySnapshot = await getDocs(productsCollectionRef); + querySnapshot.forEach((doc) => { + if(parseInt(doc.data()?.id)===parseInt(id)){ + setisAlreadyAddedInCart(true); + } + }); } catch (error) { - //console.log(error.message); + console.error('Error fetching cart products:', error); } - } - + }; + return ( <> diff --git a/src/pages/Home/index.js b/src/pages/Home/index.js index 0bc34b5..0b30d78 100644 --- a/src/pages/Home/index.js +++ b/src/pages/Home/index.js @@ -38,7 +38,6 @@ const Home = (props) => { }; const catArr = []; - useEffect(() => { prodData.length !== 0 && @@ -55,7 +54,6 @@ const Home = (props) => { setactiveTab(list2[0]) window.scrollTo(0,0); - }, []) diff --git a/src/pages/cart/index.js b/src/pages/cart/index.js index b00dfd7..049ac91 100644 --- a/src/pages/cart/index.js +++ b/src/pages/cart/index.js @@ -17,7 +17,7 @@ import { useNavigate } from "react-router-dom"; import KeyboardBackspaceIcon from "@mui/icons-material/KeyboardBackspace"; import MapComponent from "../../components/map/ITEMmap"; import { db } from "../../firebase"; -import { collection, doc, getDocs, onSnapshot } from "firebase/firestore"; +import { collection, deleteDoc, doc, getDocs, onSnapshot } from "firebase/firestore"; const Cart = () => { const [cartItems, setCartItems] = useState([]); const [error, setError] = useState(null); @@ -28,9 +28,9 @@ const Cart = () => { useEffect(() => { try { if (context.isLogin === "true") { - getCartData(); + fetchCartProducts(); } else { - navigate("/aboutus"); // Navigate to About Us page if not logged in + navigate("/signIn"); // Navigate to About Us page if not logged in } window.scrollTo(0, 0); @@ -49,90 +49,46 @@ const Cart = () => { const cartRef = doc(db, 'carts', uid); const productsCollectionRef = collection(cartRef, 'products'); const querySnapshot = await getDocs(productsCollectionRef); - const products = []; + let products = []; + let price = 0; querySnapshot.forEach((doc) => { products.push({ id: doc.id, ...doc.data() }); + price+= parseInt(doc.data()?.price)*(doc.data()?.quantity) }); - console.log(products) + context.setCartCount(products.length) setCartItems(products); + setTotalPrice(price) } catch (error) { console.error('Error fetching cart products:', error); } }; - const getCartData = async () => { + const deleteCartItem = async (uid, cartItemId) => { + const cartItemRef = doc(db, 'carts', uid, 'products', cartItemId); + try { - const db = getDatabase(); - const dataRef = ref(db, `${localStorage.getItem("user")}`); - onValue( - dataRef, - (snapshot) => { - const data = snapshot.val(); - //console.log("Data fetched successfully:", data); - if (data) { - setCartItems(Object.values(data)); - //console.log(Object.values(data).length); - // Calculate total price - const totalPrice = Object.values(data).reduce((acc, item) => { - const itemPrice = parseInt(item.price.split(",").join("")); - return acc + itemPrice * item.quantity; - }, 0); - setTotalPrice(totalPrice); - } else { - setCartItems([]); - // If data is null, set cartItems to an empty array - } - setError(null); // Reset error state if data fetch is successful - }, - (error) => { - console.error("Error fetching data:", error); - setError(error.message); // Set error state if there's an error fetching data - } - ); + await deleteDoc(cartItemRef); + fetchCartProducts() + console.log('Cart item deleted successfully.'); } catch (error) { - console.error("Error:", error); - setError("Failed to fetch data from the server"); // Set error state if there's an error with database connection + console.error('Error deleting cart item:', error); } }; - const deleteItem = async (id) => { - try { - const db = getDatabase(); - const itemRef = ref( - db, - `${localStorage.getItem("user")}/${localStorage.getItem("user")}${id}` - ); - remove(itemRef) - .then(() => { - //console.log("Item deleted successfully"); - context.removeItemsFromCart(id); - }) - .catch((error) => { - console.error("Error deleting item:", error); - }); - } catch (error) { - console.error("Error:", error); - } - }; + const deleteAllCartItems = async (uid) => { - const emptyCart = () => { + const productsCollectionRef = collection(db, 'carts', uid, 'products'); + try { - const db = getDatabase(); - const itemRef = ref(db, `${localStorage.getItem("user")}`); - remove(itemRef) - .then(() => { - context.emptyCart(); - //console.log("Item deleted successfully"); - setCartItems([]); - // Reset cartItems to an empty array after emptying the cart - setTotalPrice(0); // Reset total price - }) - .catch((error) => { - console.error("Error deleting item:", error); - }); + const querySnapshot = await getDocs(productsCollectionRef); + querySnapshot.forEach(async (doc) => { + await deleteDoc(doc.ref); + }); + await fetchCartProducts() + console.log('All cart items deleted successfully.'); } catch (error) { - console.error("Error:", error); + console.error('Error deleting cart items:', error); } }; @@ -174,7 +130,7 @@ const Cart = () => { emptyCart()} + onClick={() => deleteAllCartItems(uid)} > Clear Cart @@ -241,6 +197,7 @@ const Cart = () => { item={item} cartItems={cartItems} index={index} + quantity={item?.quantity} updateCart={updateCart} /> @@ -257,7 +214,7 @@ const Cart = () => { deleteItem(item.id)} + onClick={() => deleteCartItem(uid,`${item?.id}`)} >