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;
|
2022-06-10 16:59:25 +00:00
|
|
|
billingAddress: BillingAddress;
|
2022-02-22 17:45:01 +00:00
|
|
|
shippingAddress: ShippingAddress;
|
2022-06-10 16:59:25 +00:00
|
|
|
setBillingAddress: ( data: Partial< BillingAddress > ) => void;
|
2022-02-22 17:45:01 +00:00
|
|
|
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
|
|
|
} );
|
2022-06-10 16:59:25 +00:00
|
|
|
const { setShippingAddress, setBillingAddress } = 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,
|
2022-06-10 16:59:25 +00:00
|
|
|
billingAddress: customerData.billingAddress,
|
2020-11-20 15:13:35 +00:00
|
|
|
shippingAddress: customerData.shippingAddress,
|
2022-06-10 16:59:25 +00:00
|
|
|
setBillingAddress,
|
2020-11-20 15:13:35 +00:00
|
|
|
setShippingAddress,
|
|
|
|
};
|
|
|
|
};
|