From c8fd798f624a451a0abbd0ec7381ca3525e43ecf Mon Sep 17 00:00:00 2001 From: Philipp Stracker Date: Mon, 16 Sep 2024 17:55:19 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Update=20prefill-value=20on=20phone?= =?UTF-8?q?=20number=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../resources/js/hooks/usePhoneSyncHandler.js | 39 +++++++++++-------- 1 file changed, 23 insertions(+), 16 deletions(-) diff --git a/modules/ppcp-axo-block/resources/js/hooks/usePhoneSyncHandler.js b/modules/ppcp-axo-block/resources/js/hooks/usePhoneSyncHandler.js index ce17a8422..50baddc23 100644 --- a/modules/ppcp-axo-block/resources/js/hooks/usePhoneSyncHandler.js +++ b/modules/ppcp-axo-block/resources/js/hooks/usePhoneSyncHandler.js @@ -32,6 +32,17 @@ const getSanitizedPhoneNumber = ( select ) => { return billingPhone || shippingPhone || ''; }; +/** + * Updates the prefilled phone number in the Fastlane CardField component. + * + * @param {Object} paymentComponent - The CardField component from Fastlane + * @param {string} phoneNumber - The new phone number to prefill. + */ +const updatePrefills = ( paymentComponent, phoneNumber ) => { + console.log( 'Update the phone prefill value', phoneNumber ); + paymentComponent.updatePrefills( { phoneNumber } ); +}; + /** * Custom hook to synchronize the WooCommerce phone number with a React component state. * @@ -44,29 +55,25 @@ export const usePhoneSyncHandler = ( paymentComponent, setWooPhone ) => { getSanitizedPhoneNumber( select ) ); - // Initialize debounced setter for Fastlane. - const debouncedSetWooPhoneRef = useRef(); - - if ( ! debouncedSetWooPhoneRef.current ) { - debouncedSetWooPhoneRef.current = debounce( ( number ) => { + // Create a debounced function that updates the prefilled phone-number. + const debouncedUpdatePhone = useRef( + debounce( ( number, component ) => { setWooPhone( number ); - }, PHONE_DEBOUNCE_DELAY ); - } + updatePrefills( component, number ); + }, PHONE_DEBOUNCE_DELAY ) + ).current; - // Invoke debounced setter when phone number changes. + // Invoke debounced function when paymentComponent or phoneNumber changes. useEffect( () => { - if ( phoneNumber ) { - console.log( 'New phone number:', phoneNumber ); - debouncedSetWooPhoneRef.current( phoneNumber ); + if ( paymentComponent && phoneNumber ) { + debouncedUpdatePhone( phoneNumber, paymentComponent ); } - }, [ phoneNumber ] ); + }, [ debouncedUpdatePhone, paymentComponent, phoneNumber ] ); // Cleanup on unmount, canceling any pending debounced calls. useEffect( () => { return () => { - if ( debouncedSetWooPhoneRef.current?.cancel ) { - debouncedSetWooPhoneRef.current.cancel(); - } + debouncedUpdatePhone.cancel(); }; - }, [] ); + }, [ debouncedUpdatePhone ] ); };