Home > Back-end >  Increase qty by 1 if item already exist in cart - Reactjs/NextJS
Increase qty by 1 if item already exist in cart - Reactjs/NextJS

Time:06-18

I have found many questions similar to the subject, however, I couldn't understand the logic, as most of these are asked/explained in the PHP/ MySQL community.

I'm building an eCommerce store, where I need to handle cart items. The problem is already mentioned in the subject. Below is a short snippet of my code.

 // initial state | for testing purpos, I inserted atleast one item hardcoded 
const [cartItems, setCartItems] = useState([{id: 123, title: 'The Best', price: 55, qty: 1}])

const handleCartUpdate = (id,title, price, qty) => {
  // first checking if  cart is empty or not
  const cartLength = cartItems.legnth >=1 ? true : false
  // Check if item exist with the id as given in parameters
  if(cartLength) {
    const checkItemExist = cartItems.find(item => item.id == id)
    // Now, if item exist, update the propert 'qty' , My approach is as under:
    if (checkItemExist) {
      cartItems.map(product => {
        if(product.id == id) {
          return {product, qty: 2} // for testing purpose, I hard coded qty
        }
      }
      return setCartItems({...cartItems, ...product})
    }
  } else {
    setCartItems({...cartItems, {...}})
  }
}

After that, I am unable to understand how to update the cartItems

CodePudding user response:

The standard React-way of updating an immutable array would be to map over the items, identify whether or not an item needs an update and then return either the original or an updated copy of the item:

const [cartItems, setCartItems] = useState([]);

const handleCartUpdate = (id, title, price, qty) => {
  setCartItems(
    cartItems => cartItems.some(item => item.id === id)
      ? cartItems.map(item => item.id === id 
          ? { ...item, qty: item.qty   1 } 
          : item 
        )
      : [ ...cartItems, {id, title, price, qty} ]
  )
}

If you think this is too much boilerplate code, think about using a library like Immer to make handling immutable data easier.

CodePudding user response:

You need to just filter out the current item and increase the quantity. Then set the value to the state. I have done a simple work here. Check it is workable for you or not.

const handleCartUpdate = (id,title, price, qty) => {
const cartLength = cartItems.legnth >=1 ? true : false
if(cartLength) {
const checkItemExist = cartItems.find(item => item.id === id)
if (checkItemExist) {
  let currentItem = cartItems.filter(item=> item.id === id);
  currentItem[0].qty = currentItem[0].qty   1;
  setCartItems(...currentItem);
}
  • Related