2021-01-28 14:24:01 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { useDispatch, useSelect } from '@wordpress/data';
|
|
|
|
import { useCallback } from '@wordpress/element';
|
|
|
|
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
|
2021-04-08 12:31:12 +00:00
|
|
|
import { useThrowError } from '@woocommerce/base-hooks';
|
2021-01-28 14:24:01 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* This is a custom hook for selecting shipping rates
|
|
|
|
*
|
|
|
|
* @return {Object} This hook will return an object with these properties:
|
|
|
|
* - selectShippingRate: A function that immediately returns the selected rate and dispatches an action generator.
|
|
|
|
* - isSelectingRate: True when rates are being resolved to the API.
|
|
|
|
*/
|
2021-03-09 10:55:24 +00:00
|
|
|
export const useSelectShippingRates = (): {
|
|
|
|
selectShippingRate: (
|
|
|
|
newShippingRateId: string,
|
2021-05-10 09:03:30 +00:00
|
|
|
packageId: string | number
|
2021-03-09 10:55:24 +00:00
|
|
|
) => unknown;
|
|
|
|
isSelectingRate: boolean;
|
|
|
|
} => {
|
2021-01-28 14:24:01 +00:00
|
|
|
const throwError = useThrowError();
|
2021-03-09 10:55:24 +00:00
|
|
|
const { selectShippingRate } = ( useDispatch( storeKey ) as {
|
|
|
|
selectShippingRate: unknown;
|
|
|
|
} ) as {
|
|
|
|
selectShippingRate: (
|
|
|
|
newShippingRateId: string,
|
2021-05-10 09:03:30 +00:00
|
|
|
packageId: string | number
|
2021-03-09 10:55:24 +00:00
|
|
|
) => Promise< unknown >;
|
|
|
|
};
|
2021-01-28 14:24:01 +00:00
|
|
|
|
|
|
|
// Sets a rate for a package in state (so changes are shown right away to consumers of the hook) and in the stores.
|
|
|
|
const setRate = useCallback(
|
2021-03-09 10:55:24 +00:00
|
|
|
( newShippingRateId, packageId ) => {
|
|
|
|
selectShippingRate( newShippingRateId, packageId ).catch(
|
2021-01-28 14:24:01 +00:00
|
|
|
( error ) => {
|
|
|
|
// we throw this error because an error on selecting a rate is problematic.
|
|
|
|
throwError( error );
|
|
|
|
}
|
|
|
|
);
|
|
|
|
},
|
|
|
|
[ throwError, selectShippingRate ]
|
|
|
|
);
|
|
|
|
|
|
|
|
// See if rates are being selected.
|
2021-03-09 10:55:24 +00:00
|
|
|
const isSelectingRate = useSelect< boolean >( ( select ) => {
|
2021-01-28 14:24:01 +00:00
|
|
|
return select( storeKey ).isShippingRateBeingSelected();
|
|
|
|
}, [] );
|
|
|
|
|
|
|
|
return {
|
|
|
|
selectShippingRate: setRate,
|
|
|
|
isSelectingRate,
|
|
|
|
};
|
|
|
|
};
|