I am new in React and learning context. While learning I came across a project for creating a cart where value is added and deleted.
Adding an item part is achieved but I am not able to implement the remove functionality.
This is my Item component where I am handeling the item array and adding them
import { CartContext } from "./Cart-Context";
import { useContext } from "react";
// import { v4 as uuidv4 } from 'uuid';
import React from "react";
const Items = () => {
const ItemArr = [
{ name: "item1" },
{ name: "item2" },
{ name: "item3" },
{ name: "item4" },
{ name: "item5" },
];
const context = useContext(CartContext);
const handleClick = (item) => {
context.updateCart([...context.cart, item]);
console.log(context.cart);
};
const handleRemove = (item) =>{
const newList = context.cart.filter((newItem, key)=>{
return newItem !== key
})
console.log(newList);
}
return (
<div>
{ItemArr.map((item) => {
return (
<div>
{item.name}
<button
onClick={()=>{handleClick(item)}}
>
Add To Cart
</button>
<button onClick={()=>{handleRemove(item)}}>Remove from Cart</button>
</div>
);
})}
</div>
);
};
export default Items;
This is my provider component
import { useState } from "react";
import { CartContext } from "./Cart-Context";
const CartProvider = (props) =>{
const [cart, setCart] = useState([]);
const [removeCart, setRemoveCart] = useState([])
return (
<CartContext.Provider value={{cart: cart ,updateCart: setCart, remove: removeCart , updateRemove: setRemoveCart}}>
{
props.children
}
</CartContext.Provider>
);
}
export default CartProvider;
Now on click of remove button I want to remove that specific item from the cart array (context.cart)
2
Answers
just set new cart content:
I think your
filter
method is not correct. I assume you want to remove the provideditem
, but the filter is not referring it. You’re comparing the index of the current element with the element itself, which will always befalse
as long as the item is not a number, which is the same as the index. Also, the newly created list is not used to update the cart.I think you will keep all items in the cart which are not the provided one, so
try this instead: