import React, { useEffect, useState } from 'react'
import { HiOutlineBackspace } from "react-icons/hi";
import {MdOutlineCancel} from 'react-icons/md'
const Cart = ({toggleCart}) => {
const localStorageCart = JSON.parse(localStorage.getItem('MY_CART')) || []
const [cartItem, setCartItem] = useState(localStorageCart)
*************************************
const handleDeleteButton = (index) => {
cartItem.filter(cartItem[index])
console.log(cartItem);
}
**************************************
useEffect(() =>{
setCartItem(cartItem)
},[cartItem])
return (
<div className='cartContainer'>
<h1 style={{textAlign:"center"}}>Your Cart</h1>
<button
style={{backgroundColor:'transparent'}}
onClick={toggleCart}
>
<HiOutlineBackspace/>
</button>
<div className='cartCardContainer'>
{cartItem.map((cartItem,index) =>{
return(
<div className="cartCard" key={index}>
<img src={cartItem.img} alt="logo" id="img" />
<h2>{cartItem.title}</h2>
<div className="description">
<h5>{cartItem.description}</h5>
</div>
<div className="priceCard" >
<h3>${cartItem.price}</h3>
</div>
<button onClick={() => handleDeleteButton(index)}>***********************
<MdOutlineCancel/>
</button>
</div>
)
})}
</div>
</div>
)
}
export default Cart
I am working on an e-commerce add to Cart function.
By using useEffect I managed to rerender the cart right upon adding an item since it was a one-page app.
But when I tried to splice( ) the cartItem I heard that it is not a good practice and that I should use filter( ) instead but I am having trouble doing so as I have tried many ways and the filter doesn't go as planned or it just dont run.
For this part of the project I use a lot of Local Storage as it is the addToCart component
I have put * symbol on where I think the problem might be
The filtering is not implemented correctly. Also, you have to update the state after filtering/removing items from the state.
You can use splice() to remove an element from an array.
The following is how handleDeleteButton
should look like:
const handleDeleteButton = (index) => {
cartItem.splice(index, 1)); // 1 means remove one item only
setCartItem([...cartItem]);
}