Managing add-to-cart for large quantity of items
So far the shopping cart systems I have seen involve adding few quantity of Items to the cart and using a dropdown button (or an increment button) the users can select the quantity of product and the quantity is subtracted from quantity in stock. Using the array below I'm able to select the quantity of Items from a dropdown button. The array gets the total quantity of items in the stock.
This seems to be fine when dealing with few items in the stock. When, for example, up to 5000 items are in stock and I want to select 100 items, it will become messy to have a dropdown (or increment button) from which the total items in the stock are retrieved and user selects the quantity he wants. The length of the dropdown will be inconvenient.
[...Array(item.countInStock).keys()].map((x) => (
<option key={x + 1} value={x + 1}>
{x + 1}
</option>
))
The redux reducer is shown below
export const cartReducer = (state = { cartItems: [], shippingAddress: {} }, action) => {
switch (action.type) {
case CART_ADD_ITEM:
const item = action.payload
const existItem = state.cartItems.find(x => x.product === item.product)
if (existItem) {
return {
...state,
cartItems: state.cartItems.map(x =>
x.product === existItem.product ? item : x)
}
} else {
return {
...state,
cartItems: [...state.cartItems, item]
}
}
Add to cart handler
const addToCartHandler = () => {history.push(`/cart/${match.params.id}?qty=${qty}`)}
<Button onClick={addToCartHandler}>Add to Cart<Button>
Of course, the code runs appropriately. But I want to know what to do when the user wants to add many Items (say 100 items) to the cart. Instead of having a dropdown from which he selects from (which will not be convenient) which approach can I use to achieve this? It was suggested that I use an input field. Though I could increment the value using a button, but I'm not able to type in n the field. And what I want is to be able to input the quantity of the item not just to increment with a button
I think if you can use the input field with the type number it should solve your issue, and it's easy for the user to enter desired quantity without any hassle.
const onChange = (e => {
if(e.target.value <= item.countInStock && e.target.value > 0){
// do something
}
}
<input type="number" max={item.countInStock} min="0" onChange={checkValue}>