Skip to content
This repository has been archived by the owner on Feb 23, 2024. It is now read-only.

Commit

Permalink
Update item quantity if server result is different from client (#5352)
Browse files Browse the repository at this point in the history
* respect when quantity changes from up

* add test
  • Loading branch information
senadir authored Dec 10, 2021
1 parent eb607e8 commit 4852f7f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,9 @@ export const useStoreCartItemQuantity = (
storeKey
);

// Update local state when server updates.
useEffect( () => setQuantity( cartItemQuantity ), [ cartItemQuantity ] );

// Track when things are already pending updates.
const isPending = useSelect(
( select ) => {
Expand Down
27 changes: 27 additions & 0 deletions assets/js/blocks/cart-checkout/cart/test/block.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,4 +178,31 @@ describe( 'Testing cart', () => {
await waitFor( () => expect( fetchMock ).toHaveBeenCalled() );
expect( screen.getAllByRole( 'cell' )[ 1 ] ).toHaveTextContent( '16€' );
} );

it( 'updates quantity when changed in server', async () => {
const cart = {
...previewCart,
// Make it so there is only one item to simplify things.
items: [
{
...previewCart.items[ 0 ],
quantity: 5,
},
],
};
const itemName = cart.items[ 0 ].name;
render( <CartBlock /> );

await waitFor( () => expect( fetchMock ).toHaveBeenCalled() );
const quantityInput = screen.getByLabelText(
`Quantity of ${ itemName } in your cart.`
);
expect( quantityInput.value ).toBe( '2' );

act( () => {
dispatch( storeKey ).receiveCart( cart );
} );

expect( quantityInput.value ).toBe( '5' );
} );
} );
3 changes: 1 addition & 2 deletions assets/js/data/cart/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -393,11 +393,10 @@ export function* changeCartItemQuantity(
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- unclear how to represent multiple different yields as type
): Generator< unknown, void, any > {
const cartItem = yield select( CART_STORE_KEY, 'getCartItem', cartItemKey );
yield itemIsPendingQuantity( cartItemKey );

if ( cartItem?.quantity === quantity ) {
return;
}
yield itemIsPendingQuantity( cartItemKey );
try {
const { response } = yield apiFetchWithHeaders( {
path: '/wc/store/cart/update-item',
Expand Down

0 comments on commit 4852f7f

Please sign in to comment.