Refactor out cartItems (Discussion)
See original GitHub issueincreaseItemByOne
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)
}
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
Yes, that’s a good call, thanks @ChrisBrownie55 👍
@thorsten-stripe is the following also an acceptable format?
I find that it’s easier when you only have two arguments to just keep them separate because their names and types show up in most editors as soon as you begin using the function making dev much easier.
Also I believe it reads much better when analyzing the source code:
Whereas objects don’t require a specific order so you might end up with: