2020-11-20 15:13:35 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2022-02-22 17:45:01 +00:00
|
|
|
import { useDispatch, useSelect } from '@wordpress/data';
|
2020-11-20 15:13:35 +00:00
|
|
|
import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data';
|
2022-02-22 17:45:01 +00:00
|
|
|
import type { BillingAddress, ShippingAddress } from '@woocommerce/settings';
|
|
|
|
|
|
|
|
export interface CustomerDataType {
|
|
|
|
isInitialized: boolean;
|
|
|
|
billingData: BillingAddress;
|
|
|
|
shippingAddress: ShippingAddress;
|
|
|
|
setBillingData: ( data: Partial< BillingAddress > ) => void;
|
|
|
|
setShippingAddress: ( data: Partial< ShippingAddress > ) => void;
|
2021-05-13 10:20:37 +00:00
|
|
|
}
|
|
|
|
|
2020-11-20 15:13:35 +00:00
|
|
|
/**
|
|
|
|
* This is a custom hook for syncing customer address data (billing and shipping) with the server.
|
|
|
|
*/
|
2022-02-22 17:45:01 +00:00
|
|
|
export const useCustomerData = (): CustomerDataType => {
|
|
|
|
const { customerData, isInitialized } = useSelect( ( select ) => {
|
|
|
|
const store = select( storeKey );
|
|
|
|
return {
|
|
|
|
customerData: store.getCustomerData(),
|
|
|
|
isInitialized: store.hasFinishedResolution( 'getCartData' ),
|
2021-12-31 15:10:43 +00:00
|
|
|
};
|
2022-02-22 17:45:01 +00:00
|
|
|
} );
|
|
|
|
const { setShippingAddress, setBillingData } = useDispatch( storeKey );
|
2021-12-31 15:10:43 +00:00
|
|
|
|
2020-11-20 15:13:35 +00:00
|
|
|
return {
|
2022-02-22 17:45:01 +00:00
|
|
|
isInitialized,
|
2020-11-20 15:13:35 +00:00
|
|
|
billingData: customerData.billingData,
|
|
|
|
shippingAddress: customerData.shippingAddress,
|
|
|
|
setBillingData,
|
|
|
|
setShippingAddress,
|
|
|
|
};
|
|
|
|
};
|