2020-02-14 03:43:13 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2020-03-13 19:04:03 +00:00
|
|
|
import { useSelect } from '@wordpress/data';
|
2020-03-05 19:54:05 +00:00
|
|
|
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
|
2020-03-10 15:49:26 +00:00
|
|
|
|
2020-02-14 03:43:13 +00:00
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
2020-03-11 10:50:12 +00:00
|
|
|
import { useStoreCart } from '../cart/use-store-cart';
|
2020-03-13 19:04:03 +00:00
|
|
|
import { useShippingAddress } from '../shipping/use-shipping-address';
|
2020-02-14 03:43:13 +00:00
|
|
|
/**
|
2020-03-10 10:55:19 +00:00
|
|
|
* This is a custom hook that is wired up to the `wc/store/cart/shipping-rates` route.
|
|
|
|
* Given a a set of default fields keys, this will handle shipping form state and load
|
|
|
|
* new rates when certain fields change.
|
|
|
|
*
|
2020-02-14 03:43:13 +00:00
|
|
|
* @return {Object} This hook will return an object with three properties:
|
2020-03-10 10:55:19 +00:00
|
|
|
* - {Boolean} shippingRatesLoading A boolean indicating whether the shipping
|
|
|
|
* rates are still loading or not.
|
|
|
|
* - {Function} setShippingAddress An function that optimistically
|
|
|
|
* update shipping address and dispatches async rate fetching.
|
|
|
|
* - {Object} shippingAddress An object containing shipping address.
|
2020-03-13 13:41:59 +00:00
|
|
|
* - {Object} shippingAddress True when address data exists.
|
2020-02-14 03:43:13 +00:00
|
|
|
*/
|
2020-03-13 19:04:03 +00:00
|
|
|
export const useShippingRates = () => {
|
2020-03-10 15:49:26 +00:00
|
|
|
const { cartErrors, shippingRates } = useStoreCart();
|
2020-03-13 19:04:03 +00:00
|
|
|
const { shippingAddress, setShippingAddress } = useShippingAddress();
|
2020-03-10 10:55:19 +00:00
|
|
|
const shippingRatesLoading = useSelect(
|
|
|
|
( select ) => select( storeKey ).areShippingRatesLoading(),
|
|
|
|
[]
|
|
|
|
);
|
2020-02-14 03:43:13 +00:00
|
|
|
return {
|
|
|
|
shippingRates,
|
2020-03-10 10:55:19 +00:00
|
|
|
shippingAddress,
|
|
|
|
setShippingAddress,
|
|
|
|
shippingRatesLoading,
|
2020-03-10 15:49:26 +00:00
|
|
|
shippingRatesErrors: cartErrors,
|
2020-03-13 13:41:59 +00:00
|
|
|
hasShippingAddress: !! shippingAddress.country,
|
2020-02-14 03:43:13 +00:00
|
|
|
};
|
|
|
|
};
|