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

Update item quantity if server result is different from client #5352

Merged
merged 2 commits into from
Dec 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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