From 80a2c40dde69747d16b805053b6ef03f69acc4d3 Mon Sep 17 00:00:00 2001 From: Hemanth kumar Date: Sun, 12 May 2024 00:53:07 +0530 Subject: [PATCH] storing the cart data in firestore (#64) --- src/App.js | 27 +++++++++++++++ src/components/header/header.js | 32 +----------------- src/components/product/index.js | 19 ++++------- src/pages/AddProd/index.js | 6 ++-- src/pages/Details/index.js | 47 +++++---------------------- src/pages/SellerRegistration/index.js | 7 ++-- src/pages/SignIn/index.js | 2 ++ src/pages/cart/index.js | 25 +++++++++++++- 8 files changed, 77 insertions(+), 88 deletions(-) diff --git a/src/App.js b/src/App.js index 98c246f..bbdc9a3 100644 --- a/src/App.js +++ b/src/App.js @@ -29,6 +29,8 @@ import AddProductForm from "./pages/AddProd"; // import data from './data'; import MapComponent from "./components/map/ITEMmap"; import SellerForm from "./pages/SellerRegistration"; +import { db } from "./firebase"; +import { collection, doc, getDocs } from "firebase/firestore"; const MyContext = createContext(); @@ -48,6 +50,29 @@ function App() { const [isLogin, setIsLogin] = useState(); const [isOpenFilters, setIsopenFilters] = useState(false); const [data, setData] = useState([]); + const [cartCount,setCartCount] = useState(0) + + + useEffect(()=>{ + fetchCartProducts() + },[]) + + const fetchCartProducts = async () => { + try { + const cartRef = doc(db, 'carts', localStorage.getItem("uid")); + const productsCollectionRef = collection(cartRef, 'products'); + const querySnapshot = await getDocs(productsCollectionRef); + const products = []; + querySnapshot.forEach((doc) => { + products.push({ id: doc.id, ...doc.data() }); + }); + setCartItems(products); + setCartCount(products.length); // Set the product count + } catch (error) { + console.error('Error fetching cart products:', error); + } + }; + useEffect(() => { const fetchData = async () => { @@ -184,6 +209,8 @@ function App() { openFilters, isopenNavigation, setIsopenNavigation, + cartCount, + setCartCount }; return data && data.productData ? ( diff --git a/src/components/header/header.js b/src/components/header/header.js index 4b54e81..573a77f 100644 --- a/src/components/header/header.js +++ b/src/components/header/header.js @@ -38,8 +38,7 @@ const Header = (props) => { const [windowWidth, setWindowWidth] = useState(window.innerWidth); const [isopenSearch, setOpenSearch] = useState(false); const [isOpenNav, setIsOpenNav] = useState(false); - const [cartCount, setCartCount] = useState(0); - + const {cartCount, setCartCount} = useContext(MyContext); const headerRef = useRef(); const searchInput = useRef(); @@ -96,35 +95,6 @@ const Header = (props) => { // }) // }, []) - const getCartCount = () => { - try { - const db = getDatabase(); - const dataRef = ref(db, `${localStorage.getItem("user")}`); - - onValue( - dataRef, - (snapshot) => { - const data = snapshot.val(); - if (data) { - const itemCount = Object.values(data).length; - setCartCount(itemCount); - } else { - setCartCount(0); - } - }, - (error) => { - console.error("Error fetching data:", error); - } - ); - } catch (error) { - console.error("Error:", error); - } - }; - - useEffect(() => { - getCartCount(); - }, []); - const signOut = () => { context.signOut(); history("/"); diff --git a/src/components/product/index.js b/src/components/product/index.js index 6ad910c..fe8a0c1 100644 --- a/src/components/product/index.js +++ b/src/components/product/index.js @@ -10,6 +10,8 @@ import RemoveRedEyeOutlinedIcon from '@mui/icons-material/RemoveRedEyeOutlined'; import { getDatabase, ref, onValue, set, push, child, remove } from "firebase/database"; import { MyContext } from '../../App'; +import { db } from '../../firebase'; +import { doc, setDoc } from 'firebase/firestore'; const Product = (props) => { @@ -91,25 +93,18 @@ const Product = (props) => { } }, [userLocation, productData]); - const addToCart = async (item) => { try { - const user=localStorage.getItem('user') - // Initialize Firebase database with the provided database URL - const db = getDatabase(); - const cartRef = ref(db,user ); - // Generate a unique key using the user's email and item details - const uniqueKey = user+item.id; // Modify as per your requirement - // Add item to the cart in Firebase - await set(child(cartRef, uniqueKey), { ...item, quantity: 1 }); + const user=localStorage.getItem('uid') + const cartRef = doc(db, 'carts', user); + const productRef = doc(cartRef, 'products', `${item.id}`); + await setDoc(productRef, {...item, quantity: 1}); setIsadded(true) - // Assuming setIsAdded updates the state to indicate the item is added - //console.log('Item added to cart successfully'); + context.setCartCount(context.cartCount+1); } catch (error) { console.error('Error adding item to cart:', error); } }; - if(loading){ return
Loading...
} diff --git a/src/pages/AddProd/index.js b/src/pages/AddProd/index.js index 4d60cd1..65c2ac4 100644 --- a/src/pages/AddProd/index.js +++ b/src/pages/AddProd/index.js @@ -39,7 +39,7 @@ export default function AddProductForm() { const addProd = async (main,sub) => { // funtion to add products data to firestore try { - await addDoc(collection(db, 'sellers', `${localStorage.getItem("user")}_details`, 'products'), { + await addDoc(collection(db, 'sellers', localStorage.getItem("uid"), 'products'), { productName: formData.productName, price: formData.price, discountPrice: formData.discountPrice, @@ -70,12 +70,12 @@ export default function AddProductForm() { const handleSubmit = async () => { setIsSubmit(true) //Upload the main image to firebase storage and get url - const imageRef = ref(storage, `productImages/${localStorage.getItem("user")}/${formData.productName}/mainImage`); + const imageRef = ref(storage, `productImages/${localStorage.getItem("uid")}/${formData.productName}/mainImage`); await uploadBytes(imageRef, formData.mainImage); const imageUrl = await getDownloadURL(imageRef); //Upload the subsidiary image to firebase storage and get url - const imageRef1 = ref(storage, `productImages/${localStorage.getItem("user")}/${formData.productName}/subsidiaryImages`); + const imageRef1 = ref(storage, `productImages/${localStorage.getItem("uid")}/${formData.productName}/subsidiaryImages`); await uploadBytes(imageRef1, formData.subsidiaryImages); const imageUrl1 = await getDownloadURL(imageRef1); diff --git a/src/pages/Details/index.js b/src/pages/Details/index.js index a60894b..0e0f159 100644 --- a/src/pages/Details/index.js +++ b/src/pages/Details/index.js @@ -20,6 +20,8 @@ import { MyContext } from '../../App'; 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'; @@ -255,51 +257,20 @@ const DetailsPage = (props) => { } - - - // const addToCart = (item) => { - // context.addToCart(item); - - // setIsadded(true); - // } const addToCart = async (item) => { try { - const user=localStorage.getItem('user') - // Initialize Firebase database with the provided database URL - const db = getDatabase(); - const cartRef = ref(db,user ); - // Generate a unique key using the user's email and item details - const uniqueKey = user+item.id; // Modify as per your requirement - // Add item to the cart in Firebase - await set(child(cartRef, uniqueKey), { ...item, quantity: 1 }); + 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}`); + await setDoc(productRef, {...item, quantity: 1}); setIsadded(true) - // Assuming setIsAdded updates the state to indicate the item is added - //console.log('Item added to cart successfully'); + context.setCartCount(context.cartCount+1); } catch (error) { console.error('Error adding item to cart:', error); } }; - // Fetch data from Firebase Realtime Database -// const fetchDataFromFirebase = () => { -// try { -// // Get a reference to the database -// const db = getDatabase(); - -// // Reference to the node or path you want to fetch data from -// const dataRef = ref(db, localStorage.getItem('user')); - -// // Fetch data from the specified path -// onValue(dataRef, (snapshot) => { -// const data = snapshot.val(); -// //console.log("Data fetched successfully:", data); -// }, (error) => { -// console.error("Error fetching data:", error); -// }); -// } catch (error) { -// console.error("Error:", error); -// } -// }; - const getCartData = async (url) => { try { diff --git a/src/pages/SellerRegistration/index.js b/src/pages/SellerRegistration/index.js index ac60cd4..a1000c1 100644 --- a/src/pages/SellerRegistration/index.js +++ b/src/pages/SellerRegistration/index.js @@ -65,6 +65,7 @@ const SellerForm = () => { const addUser = async (userId,photo) => { // funtion to add sellers data to firestore try { await setDoc(doc(db, "sellers", userId), { + uid: userId, ownerName: formFields.ownerName, phoneNumber: formFields.phoneNumber, location: formFields.location, @@ -98,10 +99,10 @@ const SellerForm = () => { e.preventDefault(); setIsSubmit(true) // Generate a unique key - const uniqueKey = `${localStorage.getItem("user")}_details`; + const uniqueKey = localStorage.getItem("uid"); //Upload the shop photo image to firebase storage and get url - const imageRef = ref(storage, `sellerImages/${localStorage.getItem("user")}/shopPhoto`); + const imageRef = ref(storage, `sellerImages/${localStorage.getItem("uid")}/shopPhoto`); await uploadBytes(imageRef, formFields.shopPhoto); const imageUrl = await getDownloadURL(imageRef); @@ -112,7 +113,7 @@ const SellerForm = () => { }; useEffect(()=>{ - checkUserInSellers(`${localStorage.getItem("user")}_details`) + checkUserInSellers(localStorage.getItem("uid")) },[]) return ( diff --git a/src/pages/SignIn/index.js b/src/pages/SignIn/index.js index 786ade9..03fa0a7 100644 --- a/src/pages/SignIn/index.js +++ b/src/pages/SignIn/index.js @@ -107,6 +107,7 @@ const SignIn = () => { context.signIn(); dispatch(logIn({email:user.email})) setLoggedInUseEmail(user.email); + localStorage.setItem("uid", userCredential.user.uid); //console.log(loggedInUserEmail); history("/"); }) @@ -125,6 +126,7 @@ const SignIn = () => { localStorage.setItem("isLogin", true); const udata = replaceSpecialCharacters(result.user.email); localStorage.setItem("user", udata); + localStorage.setItem("uid", result.user.uid); context.signIn(); setLoggedInUseEmail(udata); //console.log(loggedInUserEmail); diff --git a/src/pages/cart/index.js b/src/pages/cart/index.js index a1bc0e0..b00dfd7 100644 --- a/src/pages/cart/index.js +++ b/src/pages/cart/index.js @@ -16,13 +16,15 @@ import { getDatabase, ref, onValue, remove } from "firebase/database"; 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"; const Cart = () => { const [cartItems, setCartItems] = useState([]); const [error, setError] = useState(null); const [totalPrice, setTotalPrice] = useState(0); const context = useContext(MyContext); const navigate = useNavigate(); - + const [uid,setUid] = useState(localStorage.getItem("uid")) useEffect(() => { try { if (context.isLogin === "true") { @@ -38,6 +40,27 @@ const Cart = () => { } }, []); + useEffect(() => { + fetchCartProducts() + }, [db,uid]); + + const fetchCartProducts = async () => { + try { + const cartRef = doc(db, 'carts', uid); + const productsCollectionRef = collection(cartRef, 'products'); + const querySnapshot = await getDocs(productsCollectionRef); + const products = []; + querySnapshot.forEach((doc) => { + products.push({ id: doc.id, ...doc.data() }); + }); + console.log(products) + setCartItems(products); + } catch (error) { + console.error('Error fetching cart products:', error); + } + }; + + const getCartData = async () => { try { const db = getDatabase();