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

Commit

Permalink
tidy/refactor cart item hook - separate dispatch from select
Browse files Browse the repository at this point in the history
  • Loading branch information
haszari committed Mar 6, 2020
1 parent bd2f0c9 commit 621643b
Showing 1 changed file with 19 additions and 23 deletions.
42 changes: 19 additions & 23 deletions assets/js/base/hooks/use-store-cart-item.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
/**
* External dependencies
*/
import { useSelect } from '@wordpress/data';
import { useSelect, useDispatch } from '@wordpress/data';
import { useState, useEffect } from '@wordpress/element';
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
import { useDebounce } from 'use-debounce';
Expand Down Expand Up @@ -31,40 +31,36 @@ export const useStoreCartItem = ( cartItemKey ) => {
const [ quantity, changeQuantity ] = useState( cartItem.quantity );
const [ debouncedQuantity ] = useDebounce( quantity, 400 );

const results = useSelect(
( select, { dispatch } ) => {
const store = select( storeKey );
const isPending = store.isItemQuantityPending( cartItemKey );
const { removeItemFromCart, changeCartItemQuantity } = dispatch(
storeKey
);

return {
isPending,
asyncChangeQuantity: ( newQuantity ) => {
changeCartItemQuantity( cartItemKey, newQuantity );
},
removeItem: () => {
removeItemFromCart( cartItemKey );
},
};
},
[ cartItemKey ]
const { removeItemFromCart, changeCartItemQuantity } = useDispatch(
storeKey
);

const { asyncChangeQuantity, ...plunkedResult } = results;
const asyncChangeQuantity = ( newQuantity ) => {
changeCartItemQuantity( cartItemKey, newQuantity );
};
const removeItem = () => {
removeItemFromCart( cartItemKey );
};

// Observe debounced quantity value, fire action to update server when it changes.
useEffect( () => {
if ( cartItem.quantity === debouncedQuantity ) return;
asyncChangeQuantity( debouncedQuantity );
}, [ debouncedQuantity ] );

const isPending = useSelect(
( select ) => {
const store = select( storeKey );
return store.isItemQuantityPending( cartItemKey );
},
[ cartItemKey ]
);

return {
isPending,
quantity,
changeQuantity,
removeItem,
isLoading: cartIsLoading,
cartItem,
...plunkedResult,
};
};

0 comments on commit 621643b

Please sign in to comment.