i have a book shop that has books, and the user can add those books into cart, then the total price of those books is shown in the cart, each time he add something new, the state adds that number, the probelm was the user could spam one item into the array, so i wanted to limit the number to one rare item, i managed to limit the shown books, but i didn’t know how to get the total price afterwards
below is what i tried:
function BookCard({
name,
image,
price,
author,
language,
description,
email,
exchangeable,
lendable,
year,
user,
}) {
const { setItems, setTotalPrice, items } = useContext(context);
function addToCart() {
setItems((prev) => {
const filteredItems = prev.filter((item) => {
const oldName = item.name;
return name !== oldName;
});
return [...filteredItems, { name: name, price: price }];
});
setTotalPrice((prevPrice) => {
const [newPrice] = items.slice(-1);
if (newPrice && newPrice.price !== price) return prevPrice + price;
else return price;
});
}
my context wrapper looks like this
function CartContext({ children }) {
const [cartItems, setCartItems] = useState([]);
const [currentPrice, setCurrentPrice] = useState(0);
const contextValue = {
items: cartItems,
totalPrice: currentPrice,
setTotalPrice: setCurrentPrice,
setItems: setCartItems,
};
return <context.Provider value={contextValue}>{children}</context.Provider>;
}
what i want:
only to add rare items, and get the total price of those items, thanks in advance
2
Answers
you can modify your addToCart function to handle this logic. Here’s a revised version of your addToCart function:
In this modified addToCart function:
I think you only have an issue in the
setTotalPrice
function, the rest looks fine:You would do a similar thing when removing from cart. Example: