woocommerce-paypal-payments/modules/ppcp-axo-block/resources/js/hooks/useShippingAddressChange.js

63 lines
2.1 KiB
JavaScript
Raw Normal View History

import { useCallback } from '@wordpress/element';
2024-09-13 22:30:04 +02:00
import { useAddressEditing } from './useAddressEditing';
2024-09-13 23:09:51 +02:00
import useCustomerData from './useCustomerData';
/**
* Custom hook to handle the 'Choose a different shipping address' selection.
*
* @param {Object} fastlaneSdk - The Fastlane SDK instance.
* @param {Function} setShippingAddress - Function to update the shipping address state.
* @return {Function} Callback function to trigger shipping address selection and update.
*/
2024-09-13 23:09:51 +02:00
export const useShippingAddressChange = ( fastlaneSdk, setShippingAddress ) => {
2024-09-13 22:30:04 +02:00
const { setShippingAddressEditing } = useAddressEditing();
2024-09-13 23:09:51 +02:00
const { setShippingAddress: setWooShippingAddress } = useCustomerData();
2024-09-13 22:30:04 +02:00
return useCallback( async () => {
if ( fastlaneSdk ) {
// Show shipping address selector and get the user's selection
const { selectionChanged, selectedAddress } =
await fastlaneSdk.profile.showShippingAddressSelector();
if ( selectionChanged ) {
// Update the shipping address in the custom store with the selected address
setShippingAddress( selectedAddress );
const { address, name, phoneNumber } = selectedAddress;
// Transform the selected address into WooCommerce format
2024-09-13 22:30:04 +02:00
const newShippingAddress = {
first_name: name.firstName,
last_name: name.lastName,
address_1: address.addressLine1,
address_2: address.addressLine2 || '',
city: address.adminArea2,
state: address.adminArea1 || '',
postcode: address.postalCode,
country: address.countryCode,
phone: phoneNumber.nationalNumber,
2024-09-13 22:30:04 +02:00
};
// Update the WooCommerce shipping address in the WooCommerce store
2024-09-13 22:30:04 +02:00
await new Promise( ( resolve ) => {
setWooShippingAddress( newShippingAddress );
resolve();
} );
// Trigger the Address Card view by setting the shipping address editing state to false
2024-09-13 22:30:04 +02:00
await new Promise( ( resolve ) => {
setShippingAddressEditing( false );
resolve();
} );
}
}
2024-09-13 22:30:04 +02:00
}, [
fastlaneSdk,
setShippingAddress,
setWooShippingAddress,
setShippingAddressEditing,
] );
};
export default useShippingAddressChange;