Fix bugs with optimistic.

This commit is contained in:
Lee Robinson 2024-07-25 17:15:50 -05:00
parent 0ebf071826
commit cea56f608b
2 changed files with 43 additions and 18 deletions

View File

@ -47,7 +47,7 @@ export function EditItemQuantityButton({
return ( return (
<form <form
action={async () => { action={async () => {
optimisticUpdate({ itemId: payload.lineId, newQuantity: payload.quantity }); optimisticUpdate({ itemId: payload.lineId, newQuantity: payload.quantity, type });
await actionWithVariant(); await actionWithVariant();
}} }}
> >

View File

@ -24,6 +24,7 @@ type MerchandiseSearchParams = {
type NewState = { type NewState = {
itemId: string; itemId: string;
newQuantity: number; newQuantity: number;
type: 'plus' | 'minus';
}; };
function reducer(state: Cart | undefined, newState: NewState) { function reducer(state: Cart | undefined, newState: NewState) {
@ -31,24 +32,32 @@ function reducer(state: Cart | undefined, newState: NewState) {
return state; return state;
} }
const updatedLines = state.lines.map((item: CartItem) => { let updatedLines = state.lines
if (item.id === newState.itemId) { .map((item: CartItem) => {
const singleItemAmount = Number(item.cost.totalAmount.amount) / item.quantity; if (item.id === newState.itemId) {
const newTotalAmount = Number(item.cost.totalAmount.amount) + singleItemAmount; if (newState.type === 'minus' && newState.newQuantity === 0) {
return { // Remove the item if quantity becomes 0
...item, return null;
quantity: newState.newQuantity,
cost: {
...item.cost,
totalAmount: {
...item.cost.totalAmount,
amount: newTotalAmount.toString()
}
} }
};
} const singleItemAmount = Number(item.cost.totalAmount.amount) / item.quantity;
return item; 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 newTotalQuantity = updatedLines.reduce((sum, item) => sum + item.quantity, 0);
const newTotalAmount = updatedLines.reduce( const newTotalAmount = updatedLines.reduce(
@ -56,6 +65,22 @@ function reducer(state: Cart | undefined, newState: NewState) {
0 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 { return {
...state, ...state,
lines: updatedLines, lines: updatedLines,