Having created individual contexts for my functions, I now seek to optimize them by consolidating all functions into a single context provider. The three functions that handle cart options are:
- handleAddProduct
- handleRemoveProduct
- handleCartClearance
In addition to combining the functions under one context provider, I am also looking to optimize their performance as they currently take a long time to execute.
import './App.css';
import data from './component/back/Data/data'
import Header from './component/front/Header/Header';
import { BrowserRouter as Router } from 'react-router-dom'
import Routiis from '. / component / front /Routiis/Routiis'
import { createContext, useState } from 'react';
const AddProduct = createContext();
const RemoveProduct = createContext();
const EmptyCart = createContext();
const App = () => {
const { productItems } = data;
const [cartItems, setCartItems] = useState([]);
// function for adding the product...............................................................................................
const handleAddProduct = (product) => {
const ProductExist = cartItems.find((item) => item.id === product.id)
if (ProductExist) {
setCartItems
(cartItems.map((item) => item.id === product.id ?
{...ProductExist, quantity: ProductExist.quantity + 1 } : item))
}
else {
setCartItems([...cartItems, {...product, quantity: 1 }])
}
}
// function for removing the product..............................................................................................
const handleRemoveProduct = (product) => {
const ProductExist = cartItems.find((item) => item.id === product.id)
if (ProductExist.quantity === 1) {
setCartItems(cartItems.filter((item) => item.id ! == product.id))
}
else {
setCartItems(
cartItems.map((item) => item.id === product.id ?{...ProductExist, quantity: ProductExist.quantity - 1}: item,)
)
}
}
//function for clearing the cart...................................................................................................
const handleCartClearance = ()=>{
setCartItems([]);
}
return (
<>
<div className='site-bg'>
<AddProduct.Provider value={handleAddProduct}>
<RemoveProduct.Provider value={handleRemoveProduct}>
<EmptyCart.Provider value={handleCartClearance}>
<Router>
<Header cartItems={cartItems} />
<Routiis productItems={productItems} cartItems={cartItems}/>
</Router>
</EmptyCart.Provider>
</RemoveProduct.Provider>
</AddProduct.Provider>
</div>
</>
);
}
export default App;
export { AddProduct, RemoveProduct, EmptyCart}