Skip to content

Commit

Permalink
Cart added
Browse files Browse the repository at this point in the history
  • Loading branch information
0MeMo07 committed Feb 12, 2024
1 parent f1d8fef commit 22d3bdd
Show file tree
Hide file tree
Showing 10 changed files with 315 additions and 33 deletions.
Binary file removed favicon.ico
Binary file not shown.
Binary file removed logo192.png
Binary file not shown.
Binary file removed logo512.png
Binary file not shown.
175 changes: 148 additions & 27 deletions src/app/Cart.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React, { useState } from 'react';

import React, { useState, useEffect } from 'react';
import CartProductNotFound from '../components/CartProductNotFound';
import { Link } from 'react-router-dom';
import { BsCircleFill, BsChevronCompactRight, BsChevronCompactLeft } from "react-icons/bs";
import '../css/Cart.css'

export default function Cart() {
Expand All @@ -11,6 +13,124 @@ export default function Cart() {
// }, 0)
// );
// }, [basket]);


const [ProductCount, setProductCount] = useState(0);
const [products, setProducts] = useState([]);
const [productDetails, setProductDetails] = useState([]);
useEffect(() => {
const ProductCount = JSON.parse(localStorage.getItem('Products')) || [];
setProductCount(ProductCount.length);
}, []);

useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch("https://dummyjson.com/products");
const result = await response.json();
if (result && Array.isArray(result.products)) {
setProducts(result.products);
}
} catch (error) {
console.error('Error fetching data:', error);
}
};

fetchData();
}, []);

useEffect(() => {
const fetchProductDetails = async () => {
const ProductIds = JSON.parse(localStorage.getItem('Products')) || [];
const productsDetails = [];

for (const productInfo of ProductIds) {
const productId = productInfo.id;
const productQuantity = productInfo.quantity;
const product = products.find(product => product.id === productId);

if (product) {
const productDetail = {
thumbnail: product.thumbnail,
price: product.price,
title: product.title,
description: product.description,
id: product.id,
quantity: productQuantity,
};
productsDetails.push(productDetail);
}
}

setProductDetails(productsDetails);
};

fetchProductDetails();
}, [products]);

const DeleteProduct = (productId) => {
const DeleteProducts = JSON.parse(localStorage.getItem('Products')) || [];
const updatedFavorites = DeleteProducts.filter((product) => product.id !== productId);
localStorage.setItem('Products', JSON.stringify(updatedFavorites));
setProductDetails(prevDetails => prevDetails.filter(product => product.id !== productId));
setProductCount(prevCount => prevCount - 1);
};

const AddQuantity = (productId) => {
const productsInLocalStorage = JSON.parse(localStorage.getItem('Products')) || [];
const productIndex = productsInLocalStorage.findIndex(product => product.id === productId);
if (productIndex !== -1 && productsInLocalStorage[productIndex].quantity > 0) {
productsInLocalStorage[productIndex].quantity += 1;

localStorage.setItem('Products', JSON.stringify(productsInLocalStorage));

const updatedProductDetails = productDetails.map(product => {
if (product.id === productId) {
return {
...product,
quantity: product.quantity + 1
};
}
return product;
});

setProductDetails(updatedProductDetails);
}
};

const RemoveQuantity = (productId) => {
const productsInLocalStorage = JSON.parse(localStorage.getItem('Products')) || [];
const productIndex = productsInLocalStorage.findIndex(product => product.id === productId);

if (productIndex !== -1 && productsInLocalStorage[productIndex].quantity > 0) {
productsInLocalStorage[productIndex].quantity -= 1;

if (productsInLocalStorage[productIndex].quantity === 0) {
const updatedProductsInLocalStorage = productsInLocalStorage.filter(product => product.id !== productId);
localStorage.setItem('Products', JSON.stringify(updatedProductsInLocalStorage));

const updatedProductDetails = productDetails.filter(product => product.id !== productId);
setProductDetails(updatedProductDetails);
setProductCount(prevCount => prevCount - 1);
} else {
localStorage.setItem('Products', JSON.stringify(productsInLocalStorage));

const updatedProductDetails = productDetails.map(product => {
if (product.id === productId) {
return {
...product,
quantity: product.quantity - 1
};
}
return product;
});
setProductDetails(updatedProductDetails);
}
}
};



return (
<>

Expand All @@ -23,39 +143,40 @@ export default function Cart() {
<div className="col-md-8">
<div className="product-details mr-2">
<div className="d-flex flex-row align-items-center">
<i className="fa fa-long-arrow-left"></i>
<span className="ml-2">Continue Shopping</span>
<Link to="/" className='FavİconLinks'>
<i className="fa fa-long-arrow-left"></i>
<span className="ml-2">Continue Shopping</span>
</Link>
</div>
<hr />
<h6 className="mb-0">Shopping cart</h6>
<h6 className="mb-0">Shopping Favorites</h6>
<div className="d-flex justify-content-between">
<span>You have 4 items in your cart</span>
<div className="d-flex flex-row align-items-center">
<span className="text-black-50">Sort by:</span>
<div className="price ml-2">
<span className="mr-1">price</span>
<i className="fa fa-angle-down"></i>
</div>
</div>
<span>You have {ProductCount} items in your Favorites</span>
{ProductCount === 0 && <CartProductNotFound />}
</div>

{/* Repeat this block for each item in the cart */}
<div className="d-flex justify-content-between align-items-center mt-3 p-2 items rounded">
<div className="d-flex flex-row">
<img className="rounded" src="https://i.imgur.com/QRwjbm5.jpg" width="40" alt="Product" />
<div className="ml-2">
<span className="font-weight-bold d-block">Iphone 11 pro</span>
<span className="spec">256GB, Navy Blue</span>
{productDetails.map((product, index) => (
<div key={index}>
<div className="d-flex justify-content-between align-items-center mt-3 p-2 items rounded">
<div className="d-flex flex-row">
<img className="rounded" src={product.thumbnail} width="40" alt={`${index}`} />
<div className="ml-2">
<span className="font-weight-bold d-block">{product.title}</span>
<span className="spec">{product.description}</span>
</div>
</div>
<div className="d-flex flex-row align-items-center">
<span className="d-block ml-5 font-weight-bold">${product.price}</span>
<span className="d-block ml-5 font-weight-bold" id= "AddQuantity-RemoveQuantity">
<BsChevronCompactLeft onClick={() => RemoveQuantity(product.id)} id="Leftİcon"/>
{product.quantity}
<BsChevronCompactRight onClick={() => AddQuantity(product.id)} id="Rightİcon"/>
</span>
<i className="fa fa-trash-o ml-3 text-black-50" id="Trash" onClick={() => DeleteProduct(product.id)}></i>
</div>
</div>
<div className="d-flex flex-row align-items-center">
<span className="d-block">2</span>
<span className="d-block ml-5 font-weight-bold">$900</span>
<i className="fa fa-trash-o ml-3 text-black-50"></i>
</div>
</div>
{/* Repeat block end */}

))}
</div>
</div>
<div className="col-md-4">
Expand Down
46 changes: 45 additions & 1 deletion src/app/Favorites.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Button from "@mui/material/Button";
import '../css/Favorites.css'
import '../css/Routes.css';

export default function Favorites() {
export default function Favorites({ product, total, money, basket, setBasket, value }) {
const [favoritesCount, setFavoritesCount] = useState(0);
const [products, setProducts] = useState([]);
const [productDetails, setProductDetails] = useState([]);
Expand Down Expand Up @@ -60,6 +60,49 @@ export default function Favorites() {
setFavoritesCount(prevCount => prevCount - 1);
};

const addBasket = () => {
const checkBasket = basket.find((item) => item.id === product.id);
if (checkBasket) {
checkBasket.amount += 1;
setBasket([
...basket.filter((item) => item.id !== product.id),
checkBasket,
]);
} else {
setBasket([
...basket,
{
id: product.id,
amount: 1,
},
]);
}

};
const [ProductItem, setProductItem] = useState(checkIfProduct());

function checkIfProduct(productİtemId){
const ProductsItems = JSON.parse(localStorage.getItem('Products')) || [];
return ProductsItems.includes(productİtemId)
}

const toggleProduct = (productId) => {
let ProductItems = JSON.parse(localStorage.getItem('Products')) || [];

const productIndex = ProductItems.findIndex(item => item.id === productId);

if (productIndex === -1) {

ProductItems.push({ id: productId, quantity: 1 });
} else {

ProductItems[productIndex].quantity += 1;
}

localStorage.setItem('Products', JSON.stringify(ProductItems));
setProductItem(!ProductItem);

};
return (
<>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
Expand Down Expand Up @@ -90,6 +133,7 @@ export default function Favorites() {
</div>
<div className="d-flex flex-row align-items-center">
<span className="d-block ml-5 font-weight-bold">${product.price}</span>
<Button className="d-block ml-3 font-weight-bold" onClick={() => toggleProduct(product.id)}><Link to="/cart" className='FavİconLinks'>Go To Cart </Link></Button>
<i className="fa fa-trash-o ml-3 text-black-50" id="Trash" onClick={() => DeleteFavorite(product.id)}></i>
</div>
</div>
Expand Down
Binary file added src/assets/CartEmpty.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
15 changes: 15 additions & 0 deletions src/components/CartProductNotFound.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import React from 'react';
import '../css/CartProductNotFound.css';
import emptyImage from '../assets/CartEmpty.png';
function CartProductNotFound() {
return (
<div className="cart-not-found-container">
<img src={emptyImage} alt="Empty" className="cart-empty-image" />
<h2>Oops!</h2>
<p>Your Cart list is empty.</p>
<p>Why not add some items to your Cart?</p>
</div>
);
}

export default CartProductNotFound;
68 changes: 64 additions & 4 deletions src/components/Product.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,67 @@ const HeartIcon = styled(IoIosHeart)`
// `;

function Product({ product, total, money, basket, setBasket, value }) {
const basketItem = basket.find((item) => item.id === product.id);

const [ProductItem, setProductItem] = useState(checkIfProduct(product.id));

function checkIfProduct(productİtemId){
const ProductsItems = JSON.parse(localStorage.getItem('Products')) || [];
return ProductsItems.includes(productİtemId)
}

const toggleProduct = () => {
const productId = product.id;
let ProductItems = JSON.parse(localStorage.getItem('Products')) || [];

const productIndex = ProductItems.findIndex(item => item.id === productId);

if (productIndex === -1) {

ProductItems.push({ id: productId, quantity: 1 });
} else {

ProductItems[productIndex].quantity += 1;
}

localStorage.setItem('Products', JSON.stringify(ProductItems));
setProductItem(!ProductItem);

toast.success('Product successfully added to cart', {
style: {
boxShadow: 'none',
},
});
};
const basketItem = basket.find((item) => item.id === product.id) || [];

const [productDetails, setProductDetails] = useState([]);
const [productsCount, setProductsCount] = useState(0);

const DeleteProduct = (productId) => {
const DeleteProducts = JSON.parse(localStorage.getItem('Products')) || [];
let updatedFavorites = [...DeleteProducts];
let shouldRemoveProduct = false;

updatedFavorites = updatedFavorites.map(product => {
if (product.id === productId) {
product.quantity -= 1;
if (product.quantity === 0) {
shouldRemoveProduct = true;
}
}
return product;
});

if (shouldRemoveProduct) {
updatedFavorites = updatedFavorites.filter(product => product.id !== productId);
}

localStorage.setItem('Products', JSON.stringify(updatedFavorites));
setProductDetails(updatedFavorites);
};



const addBasket = () => {
const checkBasket = basket.find((item) => item.id === product.id);
if (checkBasket) {
Expand All @@ -88,10 +147,12 @@ function Product({ product, total, money, basket, setBasket, value }) {
]);
}
setTimeout(() => {
console.log(basket)
toast.success('The product has been successfully added to the cart', {
style: {
boxShadow: 'none',
},

});
}, 0);
};
Expand Down Expand Up @@ -186,8 +247,7 @@ function Product({ product, total, money, basket, setBasket, value }) {
</Typography>
<Box display="flex" alignItems="center" marginTop="10px">
<Button
disabled={!basketItem}
onClick={removeBasket}
onClick={() => DeleteProduct(product.id)}
variant="outlined"
sx={{ marginRight: "10px" }}
>
Expand All @@ -196,7 +256,7 @@ function Product({ product, total, money, basket, setBasket, value }) {
<Button
variant="contained"
disabled={total + product.price > money}
onClick={addBasket}
onClick={toggleProduct}
sx={{ marginRight: "10px" }}
>
<İconSize><MdAddShoppingCart/></İconSize>
Expand Down
Loading

0 comments on commit 22d3bdd

Please sign in to comment.