use-shopping-cart logouse-shopping-cart

setItemQuantity()

Sets an item's quantity to a specific integer. If set to 0, the item is removed from the cart.

Basic Usage

import { useShoppingCart } from 'use-shopping-cart'

function CartItem({ itemId }: { itemId: string }) {
  const { setItemQuantity, cartDetails } = useShoppingCart()
  const item = cartDetails[itemId]

  return (
    <div className="cart-item">
      <span>{item.name}</span>

      <input
        type="number"
        value={item.quantity}
        onChange={(e) => setItemQuantity(itemId, parseInt(e.target.value))}
        min="0"
      />
    </div>
  )
}

With Dropdown Selector

function CartItem({ itemId }: { itemId: string }) {
  const { setItemQuantity, cartDetails } = useShoppingCart()
  const item = cartDetails[itemId]

  return (
    <div className="cart-item">
      <span>{item.name}</span>

      <select
        value={item.quantity}
        onChange={(e) => setItemQuantity(itemId, parseInt(e.target.value))}
      >
        {[1, 2, 3, 4, 5, 10, 15, 20].map((qty) => (
          <option key={qty} value={qty}>
            {qty}
          </option>
        ))}
      </select>
    </div>
  )
}

Complete Cart Example

function Cart() {
  const { setItemQuantity, cartDetails, cartCount } = useShoppingCart()

  if (cartCount === 0) {
    return <p>Your cart is empty</p>
  }

  return (
    <div>
      {Object.entries(cartDetails).map(([id, item]) => (
        <div key={id} className="cart-item">
          <h4>{item.name}</h4>
          <p>{item.formattedValue}</p>

          <label>
            Quantity:
            <input
              type="number"
              value={item.quantity}
              onChange={(e) =>
                setItemQuantity(id, parseInt(e.target.value) || 0)
              }
              min="0"
            />
          </label>
        </div>
      ))}
    </div>
  )
}

Notes

  • Quantity must be a non-negative integer
  • Setting quantity to 0 removes the item from cart
  • Useful for quantity pickers and dropdowns
  • Replaces the current quantity (doesn't add or subtract)

Interactive Demo

Cart Display

Total Items: 0

Cart is empty. Add items to see them here!

Bananas product photo

Bananas

Yummy yellow fruit

$4.00

Set specific quantity:

setItemQuantity() sets an exact quantity (setting to 0 removes the item)

Try setting specific quantities above! The cart state persists across all documentation pages.

On this page

Shopping Cart

Your cart is empty

Try the interactive demos on the docs pages!