From 7a011867ded85a95dad413fa0e2421d4e205608e Mon Sep 17 00:00:00 2001 From: mohammadpy8 Date: Sun, 27 Aug 2023 20:05:26 +0330 Subject: [PATCH] add to cart --- src/components/Headers.tsx | 10 +++++++--- src/context/CartContextProvider.tsx | 21 ++++++++++++++++++++- src/types/products.types.ts | 3 ++- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/components/Headers.tsx b/src/components/Headers.tsx index 26e9c1d..3cf48dc 100644 --- a/src/components/Headers.tsx +++ b/src/components/Headers.tsx @@ -1,9 +1,13 @@ -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 (
@@ -11,7 +15,7 @@ const Headers = () => { - 2 + {cart.userCart.length}
) diff --git a/src/context/CartContextProvider.tsx b/src/context/CartContextProvider.tsx index 9751846..dfc4667 100644 --- a/src/context/CartContextProvider.tsx +++ b/src/context/CartContextProvider.tsx @@ -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)); diff --git a/src/types/products.types.ts b/src/types/products.types.ts index 101290c..953fe18 100644 --- a/src/types/products.types.ts +++ b/src/types/products.types.ts @@ -8,5 +8,6 @@ export type Produts = { rating: { rate: number; count: number; - } + }, + count: number }; \ No newline at end of file