Skip to content

Commit

Permalink
Fix bugs with optimistic.
Browse files Browse the repository at this point in the history
  • Loading branch information
leerob committed Jul 25, 2024
1 parent 0ebf071 commit cea56f6
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 18 deletions.
2 changes: 1 addition & 1 deletion components/cart/edit-item-quantity-button.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function EditItemQuantityButton({
return (
<form
action={async () => {
optimisticUpdate({ itemId: payload.lineId, newQuantity: payload.quantity });
optimisticUpdate({ itemId: payload.lineId, newQuantity: payload.quantity, type });
await actionWithVariant();
}}
>
Expand Down
59 changes: 42 additions & 17 deletions components/cart/modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,38 +24,63 @@ type MerchandiseSearchParams = {
type NewState = {
itemId: string;
newQuantity: number;
type: 'plus' | 'minus';
};

function reducer(state: Cart | undefined, newState: NewState) {
if (!state) {
return state;
}

const updatedLines = state.lines.map((item: CartItem) => {
if (item.id === newState.itemId) {
const singleItemAmount = Number(item.cost.totalAmount.amount) / item.quantity;
const newTotalAmount = Number(item.cost.totalAmount.amount) + singleItemAmount;
return {
...item,
quantity: newState.newQuantity,
cost: {
...item.cost,
totalAmount: {
...item.cost.totalAmount,
amount: newTotalAmount.toString()
}
let updatedLines = state.lines
.map((item: CartItem) => {
if (item.id === newState.itemId) {
if (newState.type === 'minus' && newState.newQuantity === 0) {
// Remove the item if quantity becomes 0
return null;
}
};
}
return item;
});

const singleItemAmount = Number(item.cost.totalAmount.amount) / item.quantity;
const newTotalAmount = singleItemAmount * newState.newQuantity;

return {
...item,
quantity: newState.newQuantity,
cost: {
...item.cost,
totalAmount: {
...item.cost.totalAmount,
amount: newTotalAmount.toString()
}
}
};
}
return item;
})
.filter(Boolean) as CartItem[];

const newTotalQuantity = updatedLines.reduce((sum, item) => sum + item.quantity, 0);
const newTotalAmount = updatedLines.reduce(
(sum, item) => sum + Number(item.cost.totalAmount.amount),
0
);

// If there are no items left, return an empty cart
if (updatedLines.length === 0) {
return {
...state,
lines: [],
totalQuantity: 0,
cost: {
...state.cost,
totalAmount: {
...state.cost.totalAmount,
amount: '0'
}
}
};
}

return {
...state,
lines: updatedLines,
Expand Down

0 comments on commit cea56f6

Please sign in to comment.