【问题标题】:React, Cart & local storageReact, Cart & local storage
【发布时间】:2022-12-27 00:59:07
【问题描述】:

i'm having two problems with my carts the first is when inc / dec to an item in the cart it goes to the bottom of the item list. alse i have been trying to store the items, quantities and prices to the local storage it sts but on refreshing the page it gets deleted.

this is my cart context:

// Adding Items to cart
 const onAdd = (product, quantity) => {
const checkProductInCart = cartItems.find((item) => item.id === product.id);

setTotalPrice((prevTotalPrice) => (prevTotalPrice + Math.round((product.priceNumeric * quantity)*100)/100));
setTotalQuantities((prevTotalQuantities) => prevTotalQuantities + quantity);
//setSales(product.wasPriceNumeric - product.priceNumeric);
//setTotalSavings((prevTotalSavings) => prevTotalSavings * quantity);

if(checkProductInCart) {
   // eslint-disable-next-line
  const updatedCartItems = cartItems.map((cartProduct) => {
    if(cartProduct.id === product.id) return {
      ...cartProduct,
      quantity: cartProduct.quantity + quantity
    }
    
  })

  setCartItems(updatedCartItems);
} else {
  product.quantity = quantity;
  
  setCartItems([...cartItems, { ...product }]);
}

toast.success(` ${product.name} added to the cart.`);
localStorage.setItem('totalprice', totalPrice)
localStorage.setItem('totalquantities', totalQuantities)

} 

// Removing Items from cart
const onRemove = (product) => {
foundProduct = cartItems.find((item) => item.id === product.id);
const newCartItems = cartItems.filter((item) => item.id !== product.id);

setTotalPrice((prevTotalPrice) => prevTotalPrice -(Math.round((foundProduct.price * 
foundProduct.quantity)*100)/100));
setTotalQuantities(prevTotalQuantities => prevTotalQuantities - foundProduct.quantity);
setCartItems(newCartItems);
 }

// increase and decrease cart quanitites
const toggleCartItemQuanitity = (id, value) => {
foundProduct = cartItems.find((item) => item.id === id)
index = cartItems.findIndex((product) => product.id === id);
const newCartItems = cartItems.filter((item) => item.id !== id)

if(value === 'inc') {
  setCartItems([...newCartItems, { ...foundProduct, quantity: foundProduct.quantity + 1 } ]);
  setTotalPrice((prevTotalPrice) => (Math.round((prevTotalPrice + foundProduct.priceNumeric)*100)/100));
  setTotalQuantities(prevTotalQuantities => prevTotalQuantities + 1)
  
} else if(value === 'dec') {
  if (foundProduct.quantity > 1) {
    setCartItems([...newCartItems, { ...foundProduct, quantity: foundProduct.quantity - 1 } ]);
    setTotalPrice((prevTotalPrice) => (Math.round((prevTotalPrice - foundProduct.priceNumeric)*100)/100));
    setTotalQuantities(prevTotalQuantities => prevTotalQuantities - 1)
  }
}
}

【问题讨论】:

    标签: reactjs local-storage


    【解决方案1】:

    For your first issue you could create a copy of the cartItems. Then find the index of the matching cart item and update the quantity inside copy version of array. And then spread this array in the state.

    const toggleCartItemQuanitity = (id, value) => {
      const cartItemsCopy = [...cartItems];
      foundProductIndex = cartItemsCopy.findIndex(item => item.id === id);
    
      if (value === "inc") {
        cartItemsCopy[foundProductIndex].quantity++;
        setCartItems([...cartItemsCopy]);
        setTotalPrice(
          prevTotalPrice =>
            Math.round(
              (prevTotalPrice + cartItemsCopy[foundProductIndex].priceNumeric) * 100
            ) / 100
        );
        setTotalQuantities(prevTotalQuantities => prevTotalQuantities + 1);
      } else if (value === "dec") {
        if (foundProduct.quantity > 1) {
          cartItemsCopy[foundProductIndex].quantity--;
          setCartItems([...cartItemsCopy]);
          setTotalPrice(
            prevTotalPrice =>
              Math.round(
                (prevTotalPrice - cartItemsCopy[foundProductIndex].priceNumeric) *
                  100
              ) / 100
          );
          setTotalQuantities(prevTotalQuantities => prevTotalQuantities - 1);
        }
      }
    };
    

    【讨论】:

    • hello thank you i think this might solve the problem however i keep getting the error: Uncaught TypeError: cartItemsCopy is not iterable at toggleCartItemQuanitity now
    • My bad you need to assign […cartItems] to cartItemsCopy
    • Hoping above code would've solved your issue. To answer your next issue related to localstorage are you clearing localstorage anywhere in the code ?
    • it solved the issue thank you so much , also i did manage to set the local storage now i'm working on getting it for the user to always be able to access the products once again thank you so much
    【解决方案2】:

    I think we are doing the same project. Did you complete the project? here is what I finally did:

    enter image description here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-11
      • 2019-10-30
      • 2012-07-13
      • 2020-12-15
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 2018-02-03
      相关资源
      最近更新 更多