From e9a3c0bb6d2f18d1e479a63415249313d9c44ed1 Mon Sep 17 00:00:00 2001
From: Philipp Stracker
Date: Wed, 11 Sep 2024 16:04:08 +0200
Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20New=20hook=20to=20return=20AXO=20bi?=
=?UTF-8?q?lling=20details?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../resources/js/hooks/useCustomerData.js | 46 +++++++++++++++++++
1 file changed, 46 insertions(+)
diff --git a/modules/ppcp-axo-block/resources/js/hooks/useCustomerData.js b/modules/ppcp-axo-block/resources/js/hooks/useCustomerData.js
index 1d513f0d1..6d98196c3 100644
--- a/modules/ppcp-axo-block/resources/js/hooks/useCustomerData.js
+++ b/modules/ppcp-axo-block/resources/js/hooks/useCustomerData.js
@@ -1,5 +1,6 @@
import { useCallback, useMemo } from '@wordpress/element';
import { useDispatch, useSelect } from '@wordpress/data';
+import { useMemo } from '@wordpress/element';
export const useCustomerData = () => {
const customerData = useSelect( ( select ) =>
@@ -40,3 +41,48 @@ export const useCustomerData = () => {
]
);
};
+
+export const useTokenizeCustomerData = () => {
+ const customerData = useSelect( ( select ) =>
+ select( 'wc/store/cart' ).getCustomerData()
+ );
+
+ const isValidAddress = ( address ) => {
+ // At least one name must be present.
+ if ( ! address.first_name && ! address.last_name ) {
+ return false;
+ }
+
+ // Street, city, postcode, country are mandatory; state is optional.
+ return (
+ address.address_1 &&
+ address.city &&
+ address.postcode &&
+ address.country
+ );
+ };
+
+ // Memoize the customer data to avoid unnecessary re-renders (and potential infinite loops).
+ return useMemo( () => {
+ const { billingAddress, shippingAddress } = customerData;
+
+ // Prefer billing address, but fallback to shipping address if billing address is not valid.
+ const mainAddress = isValidAddress( billingAddress )
+ ? billingAddress
+ : shippingAddress;
+
+ return {
+ cardholderName: {
+ fullName: `${ mainAddress.first_name } ${ mainAddress.last_name }`,
+ },
+ billingAddress: {
+ addressLine1: mainAddress.address_1,
+ addressLine2: mainAddress.address_2,
+ adminArea1: mainAddress.state,
+ adminArea2: mainAddress.city,
+ postalCode: mainAddress.postcode,
+ countryCode: mainAddress.country,
+ },
+ };
+ }, [ customerData ] );
+};