Skip to content

Commit

Permalink
add to cart
Browse files Browse the repository at this point in the history
  • Loading branch information
mohammadpy8 committed Aug 27, 2023
1 parent 3cdbd66 commit 7a01186
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
10 changes: 7 additions & 3 deletions src/components/Headers.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import React from 'react'
import React, {useContext} from 'react'

import { AiOutlineShoppingCart } from 'react-icons/ai';
import { Link } from "react-router-dom";
import { Link, useInRouterContext } from "react-router-dom";
import { CartContext } from '../context/CartContextProvider';

const Headers = () => {

const cart = useContext(CartContext);

return (
<header>
<Link className="logo" to="/">
shop cart
</Link>
<Link to="/cart">
<AiOutlineShoppingCart className="shop-icon" />
<span>2</span>
<span>{cart.userCart.length}</span>
</Link>
</header>
)
Expand Down
21 changes: 20 additions & 1 deletion src/context/CartContextProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,26 @@ const CartContextProvider = ({ children }: CartProps) => {
.catch((err) => console.log(err))
}, [])

const addProduts = (id: number) => {}
const addProduts = (id: number) => {
setUserCart(prevProducts => {

const mainProductInCart = userCart.find(product => product.id === id);

if (mainProductInCart) {
return prevProducts.map(product => {
if (product.id === id) {
return {...product, count:product.count + 1}
} else {
return product;
}
})
} else {
const mainProductInShop = shop.find(product => product.id === id) as Produts;
return [...prevProducts, {...mainProductInShop, count:1}]
}
return []
})
}

const removeProduts = (id: number) => setUserCart(prevProducts => prevProducts.filter(product => product.id !== id));

Expand Down
3 changes: 2 additions & 1 deletion src/types/products.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,6 @@ export type Produts = {
rating: {
rate: number;
count: number;
}
},
count: number
};

0 comments on commit 7a01186

Please sign in to comment.