Skip to content

Commit

Permalink
retrive fixed (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hemu21 authored May 12, 2024
1 parent 787907d commit b45f6c6
Show file tree
Hide file tree
Showing 6 changed files with 67 additions and 111 deletions.
6 changes: 3 additions & 3 deletions src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function App() {

useEffect(()=>{
fetchCartProducts()
},[])
},[isLogin])

const fetchCartProducts = async () => {
try {
Expand Down Expand Up @@ -96,7 +96,6 @@ function App() {

useEffect(() => {
getData();
getCartData();

const is_Login = localStorage.getItem("isLogin");
setIsLogin(is_Login);
Expand Down Expand Up @@ -210,7 +209,8 @@ function App() {
isopenNavigation,
setIsopenNavigation,
cartCount,
setCartCount
setCartCount,
fetchCartProducts
};

return data && data.productData ? (
Expand Down
4 changes: 2 additions & 2 deletions src/components/product/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
31 changes: 20 additions & 11 deletions src/components/quantityBox/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -41,13 +53,12 @@ const QuantityBox = (props) => {
<span className='arrow plus'

onClick={
() => {
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);

Expand All @@ -59,17 +70,15 @@ const QuantityBox = (props) => {

<span className='arrow minus'
onClick={
() => {
async () => {
if (inputValue !== 1) {
setinputValue(inputValue - 1)
}

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);

Expand Down
36 changes: 14 additions & 22 deletions src/pages/Details/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';



Expand Down Expand Up @@ -117,7 +117,6 @@ const DetailsPage = (props) => {
setActiveSize(index);
}


const plus = () => {
setinputValue(inputValue + 1)
}
Expand All @@ -129,8 +128,6 @@ const DetailsPage = (props) => {
}




useEffect(() => {
window.scrollTo(0, 0)
setIsLoading(true);
Expand Down Expand Up @@ -181,7 +178,7 @@ const DetailsPage = (props) => {

showReviews();

getCartData("https://mavrick-1.github.io/DataApi/data.json");
fetchCartProducts()

setIsLoading(false);

Expand Down Expand Up @@ -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}`);
Expand All @@ -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 (
<>

Expand Down
2 changes: 0 additions & 2 deletions src/pages/Home/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ const Home = (props) => {
};

const catArr = [];

useEffect(() => {

prodData.length !== 0 &&
Expand All @@ -55,7 +54,6 @@ const Home = (props) => {
setactiveTab(list2[0])

window.scrollTo(0,0);

}, [])


Expand Down
99 changes: 28 additions & 71 deletions src/pages/cart/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
Expand All @@ -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);
}
};

Expand Down Expand Up @@ -174,7 +130,7 @@ const Cart = () => {

<span
className="ml-auto clearCart d-flex align-items-center cursor "
onClick={() => emptyCart()}
onClick={() => deleteAllCartItems(uid)}
>
<DeleteOutlineOutlinedIcon /> Clear Cart
</span>
Expand Down Expand Up @@ -241,6 +197,7 @@ const Cart = () => {
item={item}
cartItems={cartItems}
index={index}
quantity={item?.quantity}
updateCart={updateCart}
/>
</td>
Expand All @@ -257,7 +214,7 @@ const Cart = () => {
<td align="center">
<span
className="cursor"
onClick={() => deleteItem(item.id)}
onClick={() => deleteCartItem(uid,`${item?.id}`)}
>
<DeleteOutlineOutlinedIcon />
</span>
Expand Down

0 comments on commit b45f6c6

Please sign in to comment.