increaseItemByOne
for the same reason we have reduceItemByOne
As the code currently stands, we have a reduceItemByOne(sku)
that handles removing one item from the cartItems
subsequently causing cartDetails
to update. This makes decreasing the number of items in a cart very intuitive from a developer standpoint. By contrast, it's not very intuitive that you're supposed to re-use addItem(product)
since at this point in the code you don't have access to your original product
object and instead you're likely operating on a cartEntry
(entry in cartDetails
).
This could be easily implemented as it's only to improve DX, however, I also have another proposal:
Replace cartItems
with cartDetails
entirely?
Currently, cartItems
is only used to generate cartDetails
, totalPrice
, and cartCount
. I'm proposing that we do away with cartItems
in favor of a more event based approach to creating and modifying the above pieces of data.
For example, instead of adding an item to the cart and generating our data from cartItems
with formatDetailedCart
, calculateTotalValue
, and cartCount
we could use reducers that handle the events in different ways.
For the calculation of cartCount
it would be something similar to the following:
function cartCountReducer(value, action) {
switch (action.type) {
case 'addItemToCart':
case 'incrementItemByOne':
return value + 1
case 'reduceItemByOne':
return value - 1
default:
return value
}
}
And of course, we need to handle certain things like if reduceItemByOne
or `incrementItemByOne are called with an invalid sku. This can be handled inside of the combined dispatch function like so:
function dispatch(action) {
// increment or reduce item by one only if there's a matching `sku` in `cartDetails`
if ((action.type === 'incrementItemByOne' || action.type === 'reduceItemByOne') && !(action.sku in cartDetails)) {
return
}
cartCountDispatch(action)
}