skip to Main Content

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


  1. you can modify your addToCart function to handle this logic. Here’s a revised version of your addToCart function:

    function addToCart() {
      // Check if the item is already in the cart
      const itemIndex = items.findIndex((item) => item.name === name);
    
      // If the item is not in the cart or it's a rare item, add it to the cart
      if (itemIndex === -1 || isRareItem(name)) {
        setItems((prev) => {
          // Remove any existing occurrences of the same item from the cart
          const filteredItems = prev.filter((item) => item.name !== name);
    
          // Add the new item to the cart
          return [...filteredItems, { name: name, price: price }];
        });
    
        // Recalculate the total price based on the current items in the cart
        setTotalPrice((prevPrice) => prevPrice + price);
      }
    }
    
    // Function to determine if an item is rare
    function isRareItem(itemName) {
      // Implement your logic here to determine if the item is rare
      // For example, you could check against a list of rare items or any other criteria
      // Return true if the item is rare, otherwise return false
      return itemName === "RareItem";
    }
    

    In this modified addToCart function:

    1. It first checks if the item is already in the cart by searching for its index in the items array.
    2. If the item is not found in the cart or if it’s a rare item (determined by the isRareItem function), it adds the item to the cart.
    3. It then recalculates the total price based on the updated items in the cart.
    Login or Signup to reply.
  2. I think you only have an issue in the setTotalPrice function, the rest looks fine:

        setTotalPrice((currentPrice) => {
          // this ensures you won't double-add the price to the existing total
          if (items.find((item) => item.name === name)) {
            return items.reduce((acc, item) => {
              return acc + item.price;
            }, 0);
          }
          // and if the item is not in the array, then add the price
          return price + currentPrice;
        });
    

    You would do a similar thing when removing from cart. Example:

    
        removeFromCart: (name) => {
          setCartItems((prev) => {
            return prev.filter((item) => item.name !== name);
          });
          setCurrentPrice((currentPrice) => {
            return (
              currentPrice - cartItems.find((item) => item.name === name).price
            );
          });
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search